@sealant/mend 0.36.0-next.754 → 0.36.0-next.768

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.
Files changed (95) hide show
  1. package/README.md +17 -8
  2. package/dist/{chunk-ARGA4E7A.js → chunk-BXXA4JXE.js} +78 -3
  3. package/dist/{dashboard-JGR77HVG.js → dashboard-URVZ54OS.js} +16 -27
  4. package/dist/main.js +1129 -448
  5. package/man/mend-accounts.1 +1 -1
  6. package/man/mend-adopt.1 +1 -1
  7. package/man/mend-attach.1 +1 -1
  8. package/man/mend-codex.1 +1 -1
  9. package/man/mend-completions.1 +1 -1
  10. package/man/mend-connect-pi.1 +1 -1
  11. package/man/mend-connect.1 +1 -1
  12. package/man/mend-continue.1 +1 -1
  13. package/man/mend-doctor.1 +2 -2
  14. package/man/mend-dotfiles-repo.1 +1 -1
  15. package/man/mend-dotfiles-sync.1 +1 -1
  16. package/man/mend-dotfiles.1 +1 -1
  17. package/man/mend-env-cluster.1 +1 -1
  18. package/man/mend-env-load.1 +1 -1
  19. package/man/mend-env-show.1 +1 -1
  20. package/man/mend-folder-create.1 +1 -1
  21. package/man/mend-folder-list.1 +1 -1
  22. package/man/mend-folder-push.1 +1 -1
  23. package/man/mend-folder-rm.1 +1 -1
  24. package/man/mend-git-author.1 +1 -1
  25. package/man/mend-help.1 +1 -1
  26. package/man/mend-invite.1 +1 -1
  27. package/man/mend-keys-init.1 +1 -1
  28. package/man/mend-keys-mode.1 +1 -1
  29. package/man/mend-keys-share.1 +1 -1
  30. package/man/mend-keys-show.1 +1 -1
  31. package/man/mend-land.1 +1 -1
  32. package/man/mend-login.1 +10 -2
  33. package/man/mend-logout.1 +1 -1
  34. package/man/mend-logs.1 +1 -1
  35. package/man/mend-man.1 +1 -1
  36. package/man/mend-members.1 +1 -1
  37. package/man/mend-memory-import.1 +1 -1
  38. package/man/mend-memory-rm.1 +1 -1
  39. package/man/mend-memory-show.1 +1 -1
  40. package/man/mend-memory.1 +1 -1
  41. package/man/mend-models.1 +1 -1
  42. package/man/mend-operator-exposure.1 +1 -1
  43. package/man/mend-operator-gate.1 +1 -1
  44. package/man/mend-operator-grant-owner.1 +1 -1
  45. package/man/mend-operator-org-create.1 +1 -1
  46. package/man/mend-operator-org-invite-owner.1 +1 -1
  47. package/man/mend-operator-org-list.1 +1 -1
  48. package/man/mend-operator-org-rename.1 +1 -1
  49. package/man/mend-operator-reset-link.1 +1 -1
  50. package/man/mend-pair.1 +1 -1
  51. package/man/mend-projects.1 +1 -1
  52. package/man/mend-pull.1 +1 -1
  53. package/man/mend-refresh.1 +1 -1
  54. package/man/mend-rejoin.1 +1 -1
  55. package/man/mend-resume.1 +1 -1
  56. package/man/mend-run.1 +1 -1
  57. package/man/mend-secrets-add.1 +1 -1
  58. package/man/mend-secrets-rm.1 +1 -1
  59. package/man/mend-secrets.1 +1 -1
  60. package/man/mend-server-logs.1 +1 -1
  61. package/man/mend-server-restart.1 +1 -1
  62. package/man/mend-server-setup.1 +7 -5
  63. package/man/mend-server-start.1 +1 -1
  64. package/man/mend-server-status.1 +1 -1
  65. package/man/mend-server-stop.1 +1 -1
  66. package/man/mend-server-upgrade.1 +1 -1
  67. package/man/mend-server.1 +1 -1
  68. package/man/mend-service-add.1 +1 -1
  69. package/man/mend-service-connect.1 +1 -1
  70. package/man/mend-service-init.1 +1 -1
  71. package/man/mend-service-list.1 +1 -1
  72. package/man/mend-service-logs.1 +1 -1
  73. package/man/mend-service-restart.1 +1 -1
  74. package/man/mend-service-run.1 +1 -1
  75. package/man/mend-service-stop.1 +1 -1
  76. package/man/mend-session-share.1 +1 -1
  77. package/man/mend-sessions.1 +1 -1
  78. package/man/mend-shell.1 +1 -1
  79. package/man/mend-skills-push.1 +1 -1
  80. package/man/mend-skills.1 +1 -1
  81. package/man/mend-snake.1 +1 -1
  82. package/man/mend-ssh-keys-remove.1 +1 -1
  83. package/man/mend-ssh-keys.1 +1 -1
  84. package/man/mend-ssh-setup.1 +1 -1
  85. package/man/mend-ssh.1 +12 -3
  86. package/man/mend-stop.1 +1 -1
  87. package/man/mend-ui.1 +1 -1
  88. package/man/mend-uninstall.1 +2 -2
  89. package/man/mend-version.1 +1 -1
  90. package/man/mend-wait.1 +1 -1
  91. package/man/mend-workspace-replace.1 +1 -1
  92. package/man/mend-worktrees-rm.1 +1 -1
  93. package/man/mend-worktrees.1 +1 -1
  94. package/man/mend.1 +2 -2
  95. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -1,6 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- AGENT_MEMORY_FILES,
4
3
  AGENT_MEMORY_MAX_DATABASE_BYTES,
5
4
  AGENT_MEMORY_MAX_FILE_BYTES,
6
5
  AGENT_MEMORY_ROOTS,
@@ -19,8 +18,10 @@ import {
19
18
  PI_PROFILE_MAX_FILE_BYTES,
20
19
  REPLACE_WORKSPACE_ACTION,
21
20
  WORKTREE_REMOVAL_FORCE_HINT,
21
+ adoptedGitAuth,
22
22
  agentIsLive,
23
23
  agentMemoryNameOf,
24
+ agentMemoryPathOf,
24
25
  agentStartingFacts,
25
26
  agentStartingLine,
26
27
  askYesNo,
@@ -79,10 +80,10 @@ import {
79
80
  workspaceRetirementLine,
80
81
  worktreeJoinLine,
81
82
  worktreeListsPeople
82
- } from "./chunk-ARGA4E7A.js";
83
+ } from "./chunk-BXXA4JXE.js";
83
84
 
84
85
  // src/main.ts
85
- import { spawn as spawn3, spawnSync as spawnSync6 } from "node:child_process";
86
+ import { spawn as spawn3, spawnSync as spawnSync7 } from "node:child_process";
86
87
  import * as crypto from "node:crypto";
87
88
  import * as fs21 from "node:fs";
88
89
  import { createRequire } from "node:module";
@@ -163,7 +164,7 @@ var memoryDisplayName = (filePath) => {
163
164
  if (named === null) return filePath;
164
165
  return named.harness === "claude" ? named.name : `${named.harness}:${named.name}`;
165
166
  };
166
- var lost = (n, whose) => `${n} of ${whose} line${n === 1 ? " is" : "s are"} not in the result: its copy kept as a version`;
167
+ var lost = (n, whose2) => `${n} of ${whose2} line${n === 1 ? " is" : "s are"} not in the result: its copy kept as a version`;
167
168
  var ADDED_NAMED = 20;
168
169
  var importReportLines = (report) => {
169
170
  const lines = [];
@@ -2170,15 +2171,18 @@ var COMMANDS = [
2170
2171
  name: "login",
2171
2172
  section: "start",
2172
2173
  summary: "sign this terminal in through the browser",
2173
- synopsis: ["[--url <server>]"],
2174
+ synopsis: ["[--url <server>] [--open | --no-open]"],
2174
2175
  description: [
2175
- "Opens <server>/authorize in your browser. You press Authorize there. The CLI saves a device token to ~/.config/mend/cli.json with mode 0600. No password is typed in the terminal, and the token can be revoked from the server at any time."
2176
+ "Opens <server>/authorize in your browser. You press Authorize there. The CLI saves a device token to ~/.config/mend/cli.json with mode 0600. No password is typed in the terminal, and the token can be revoked from the server at any time.",
2177
+ "Over SSH, or on Linux with no display, no browser opens: the CLI prints the link and the code, and you open the link on your own machine."
2176
2178
  ],
2177
2179
  options: [
2178
2180
  {
2179
2181
  flag: "--url <server>",
2180
2182
  text: "the Mend server. Default: MEND_URL, then http://localhost:3105"
2181
- }
2183
+ },
2184
+ { flag: "--open", text: "open the browser here, even over SSH" },
2185
+ { flag: "--no-open", text: "only print the link and the code" }
2182
2186
  ],
2183
2187
  examples: [
2184
2188
  { command: "mend login --url http://10.0.0.216:3105", text: "sign in to a LAN server" }
@@ -2342,7 +2346,7 @@ var COMMANDS = [
2342
2346
  summary: "check this machine's setup, or bundle it for a bug report",
2343
2347
  synopsis: ["", "--bundle [--out <path>] [--tail <n>]"],
2344
2348
  description: [
2345
- "Read-only. One line per fact: the server, the sign-in, the platform connection, the provider accounts, the git key, and where docker is on PATH its daemon's shutdown-timeout against the capture grace. Each unfinished line ends with the command that fixes it.",
2349
+ "Read-only. One line per fact: the server, the sign-in, the platform connection, the provider accounts, the git key, and where docker is on PATH what a stop of its daemon waits for against what systemd allows docker.service. Each unfinished line ends with the command that fixes it.",
2346
2350
  "--bundle collects what a maintainer asks for one output at a time into one tar.gz: this CLI and its environment, the doctor lines, the server's health, the local server's configuration (its compose file and the names of its .env keys, never their values), docker version, info, contexts, the Mend and workspace containers with their inspect facts, the local server's container logs, the running workspace containers' logs, every session with its processes, exit codes and argv, the recorded terminal output of each, the connected accounts, and the versions and paths of claude, codex, gh, git and docker on this machine.",
2347
2351
  "Each part is collected on its own: one that fails leaves a <name>.error.txt in the bundle instead of stopping it. One redactor runs over every file before it is written: bearer and header values, Slack, OpenAI, GitHub and AWS token shapes, JWTs, passwords in URLs, and any password, secret or token value. The archive is written with mode 0600. It still contains logs and configuration; read it before you share it."
2348
2352
  ],
@@ -3298,15 +3302,16 @@ var COMMANDS = [
3298
3302
  ],
3299
3303
  description: [
3300
3304
  "On a terminal with no flags, setup asks its questions in plain words, one at a time: how people reach this Mend (just this machine, your private network or Tailscale, or the public internet with HTTPS), whether VS Code Remote-SSH reaches it from other machines, the T3 Code gateway, the mirrors, and one organization or several. It looks before it asks and says what it observed: Tailscale's name and address and what Tailscale Serve forwards, where your domain resolves, and whether ports 80 and 443 are taken. It never asks for an address to bind: that follows from the answers. On an existing install it shows what is saved and lets you keep it, change one thing, or go through every question. It ends with what changes, in words, and the same command with flags; nothing applies until you say yes.",
3301
- "Flags are for scripts and CI, and teach what the questions do. Each changes only what it names; everything else is kept from the saved install, so mend server setup --t3-gateway turns the gateway on and nothing more. When there is an install, a run with flags says what it changes. With no terminal and no flags, a fresh install is refused rather than guessed: --yes takes the defaults.",
3305
+ "Flags are for scripts and CI, and teach what the questions do. Each changes only what it names; everything else is kept from the saved install, so mend server setup --t3-gateway turns the gateway on and nothing more. When there is an install, a run with flags says what it changes. With no terminal and no flags, a fresh install is refused rather than guessed: --yes takes the defaults. --context and --docker-socket choose the Docker engine and answer no question, so with only those (on a Mac with Docker Desktop and OrbStack, --context orbstack) setup still asks its questions. A fresh install without --context takes DOCKER_CONTEXT, as docker does; an existing one stays on the context its data is on.",
3306
+ "Before anything is pulled, setup checks that Mend's web and SSH ports are free where they are to be published, and says what holds one that is not: another Mend, with its version, or something else. On a terminal it offers the next free port; with flags it refuses and names --port or --ssh-port. After starting, it reads health until this install answers: its version, and the instance id the server reports, so another Mend on the same port is said as one, never taken for this one.",
3302
3307
  "Checks a local Unix-socket Docker context and the Compose plugin, downloads the compose and Postgres initialization assets for one Mend release, preserves existing data and secrets, and starts the server. Re-running repairs the same pinned version. A changed --version is refused; use mend server upgrade. Updating this CLI never updates an existing server pin.",
3303
3308
  "The default listens only on localhost at http://localhost:3105. Non-local access requires both --bind and --url. Every extra browser origin must be named with --origin; setup never guesses from the request Host header or network interfaces. A fresh install refuses a public --bind address: until the first account exists, registration is open to whoever reaches it first. On an existing install, setup says when Mend's port or workspace SSH is published on a public address while the exposure is not public. The questions offer only private addresses (a tailnet, a LAN or VPN, carrier-grade NAT space) for a private network.",
3304
3309
  "--edge <host> runs a TLS edge in front of Mend: Caddy on ports 80 and 443 of every interface, which obtains and renews a certificate for the host and proxies to Mend's web tier. Mend's own port stays on loopback and the browser origin is https://<host>. The edge's compose overlay and Caddyfile are written into the generation beside compose.yaml, so start, restart and upgrade run them every time. --no-edge takes it away again, and the edge's container with it. A fresh install cannot start with the edge: until the first account exists, registration is open to whoever reaches the origin first, so set up on localhost, create the account, then add the edge.",
3305
3310
  "--t3-gateway turns on the t3code gateway (docs/adr/0012): t3code's desktop, mobile and web clients add it as an environment, pair with a code from mend pair, and see this Mend's projects and sessions. It runs in the Mend container, confined to a root and a uid of its own, on a listener of its own published on 127.0.0.1 only (port 3120, or --t3-gateway-port): reaching it from another machine is an exposure you put in front of it and declare. Setup refuses it on a Mend image that has no gateway, and says whether it answered. It is kept across reruns and upgrades; --no-t3-gateway turns it off, and its state stays in its own volume, mend-t3-gateway. Off, nothing of it runs.",
3306
3311
  "--exposure declares how the instance is reached, and --tenancy whether one organization or many use it. Both are written into the generation and kept across reruns and upgrades. public needs the edge and an existing first account. With multi, or with public, the multi mode gate's settings follow: MEND_SOURCE_POLICY=tenant and MEND_CAPTURE_REQUIRE_SIZES=true, and public sets MEND_URL_BEARERS=refuse. The server still decides whether it starts, and mend server status shows what it reports.",
3307
3312
  "Two mirrors run beside Mend unless turned off: an npm mirror (nginx caching npmjs.org, capped at 10g by default, least recently used out) and a Docker mirror (a pull-through cache of Docker Hub, capped at 20g by default: over the cap its cache is cleared). Both leave 5g free on their disk: below that, nginx evicts and the Docker mirror pauses, and sessions pull from Docker Hub directly. Neither publishes a host port. Sessions install npm packages and pull Docker Hub images through them; a project's own npm settings win, and a mirror that is down sends sessions upstream instead. Both are kept across reruns and upgrades, and an upgrade adds them to an install from before them. The Docker mirror pulls anonymously unless given a Docker Hub login: --docker-hub-username with the access token piped on standard input, kept in server.env only. The mirror has no login of its own, so every session that reaches it can pull whatever that token can read: setup takes a login only with --docker-hub-public-only, your statement that the token's access permission is Public Repo Read-only. Mend cannot check a token's scope.",
3308
- "Before anything is pulled, setup reads the Docker host's kernel. Each workspace runs its own rootless Docker, which needs unprivileged user namespaces; Ubuntu 23.10 and later (24.04 LTS included) refuse them by default, and then no session can start. On a terminal setup asks to allow them: on a yes it writes the setting to /etc/sysctl.d/60-mend-rootless-docker.conf on the Docker host and applies it, through a short privileged container on the Docker socket it already uses, then reads the kernel again. That lifts the restriction for the whole host; the file says on its first lines that setup wrote it and what it replaced, so mend uninstall --all removes it and puts that back. On a no, without a terminal, or on a rootless daemon, it prints the command to run on the host, and repeats it as its last line. --allow-userns and --no-allow-userns answer for a script.",
3309
- "When setup changes Mend's URL, a CLI signed in at the old one is left pointing there. Setup says so with the command each one runs (mend login --url <new>). When this machine's own CLI points at the old URL and that no longer answers, setup offers to point it at the new one; its sign-in carries over, since a device's token is not bound to a URL. A re-run says to create the first account only while the instance has none.",
3313
+ "Before its other questions and before it pulls the release, setup reads the Docker host's kernel, through the few megabytes of busybox every install needs anyway. Each workspace runs its own rootless Docker, which needs unprivileged user namespaces; Ubuntu 23.10 and later (24.04 LTS included) refuse them by default, and then no session can start. On a terminal setup asks to allow them: on a yes it writes the setting to /etc/sysctl.d/60-mend-rootless-docker.conf on the Docker host and applies it, through a short privileged container on the Docker socket it already uses, then reads the kernel again. That lifts the restriction for the whole host; the file says on its first lines that setup wrote it and what it replaced, so mend uninstall --all removes it and puts that back. On a no, or on a rootless daemon, it prints the command to run on the host, and repeats it as its last line. Without a terminal or with --yes, it says to re-run with --allow-userns, so that setup writes the file and mend uninstall can undo it; the command is the other way, and a file written by hand stays on uninstall. --allow-userns and --no-allow-userns answer for a script.",
3314
+ "When setup changes Mend's URL, a CLI signed in at the old one is left pointing there. Setup says so with the command each one runs (mend login --url <new>), which is a new sign-in: it asks for a browser authorization. When this machine's own CLI points at the old URL and that no longer answers, setup offers to point it at the new one; its sign-in carries over, since a device's token is not bound to a URL. When it points anywhere else this install does not answer (another server, or nothing), setup offers the same; a sign-in made at another server stays behind, and the offer leads with no while that server answers. A re-run says to create the first account only while the instance has none.",
3310
3315
  "Docker Desktop on Linux and macOS, and OrbStack on macOS, expose client-side proxy sockets. Containers use the daemon-side /var/run/docker.sock. --docker-socket overrides detection and is retained on reruns.",
3311
3316
  "Setup holds an exclusive process lock through startup and health checks. A busy lock reports its owner and manual recovery steps. Never remove a live lock. Private configuration uses immutable generations and an atomic active pointer; failed attempts retain credentials and never delete Docker volumes."
3312
3317
  ],
@@ -3317,7 +3322,7 @@ var COMMANDS = [
3317
3322
  },
3318
3323
  {
3319
3324
  flag: "--context <name>",
3320
- text: "local Docker context to persist; the global context is unchanged"
3325
+ text: "local Docker context to persist; the global context is unchanged. Answers no question. Default: DOCKER_CONTEXT on a fresh install, else the saved one"
3321
3326
  },
3322
3327
  {
3323
3328
  flag: "--version <v>",
@@ -3558,9 +3563,13 @@ var COMMANDS = [
3558
3563
  {
3559
3564
  name: "ssh",
3560
3565
  section: "this machine",
3561
- summary: "workspace SSH status: gateway, registered keys, ssh config",
3562
- synopsis: ["[status]"],
3563
- description: ["Whether this machine can ssh into workspaces, and what is missing if not."],
3566
+ summary: "workspace SSH status, or the ssh command for one session",
3567
+ synopsis: ["[status]", "<session> [--host <hostname>]"],
3568
+ description: [
3569
+ "Without a session: whether this machine can ssh into workspaces, and what is missing if not.",
3570
+ "With a session id or its prefix: the exact ssh command that reaches that session's workspace, on its own line, e.g. ssh ws-<workspace>@mend-ws-\u2026. The user is the workspace's id, which no other command shows; a Docker container name is a different id, and the gateway closes the connection after its banner. A session with no running workspace is refused."
3571
+ ],
3572
+ examples: [{ command: "mend ssh 3f2a9c1e", text: "print the ssh command for that session" }],
3564
3573
  see: ["ssh setup", "ssh keys"]
3565
3574
  },
3566
3575
  {
@@ -3632,7 +3641,7 @@ var COMMANDS = [
3632
3641
  "Asks which scope to remove when none is given, prints exactly what will go, and requires the word delete before the server is touched; any other answer removes nothing and exits 1. Nothing is touched until Docker answers: with Docker stopped, the server and everything scopes refuse and change nothing, here or on the server.",
3633
3642
  "The server scope removes the local Compose installation. First its sessions' workspaces, live ones included: the plan lists them, and uninstall stops them and removes them with their Docker services, volumes and networks. Then its containers, every volume and network it owns (repositories, worktrees, the database), its release image, and the private configuration with its generations and backups. A workspace is the installation's when it mounts the installation's control volume. The anchor volume mend-store and identity.env go last, once everything else has; anything Docker would not remove keeps them, is named, and is written to uninstall-left.json, so running mend uninstall again finishes the job, and mend server setup can reinstall over it. A sign-in to the server just removed is cleared: its token went with the server.",
3634
3643
  "The home scope removes cli.json, the workspace SSH key file and the managed block in ~/.ssh/config. When the sign-in is to another server, that server is first asked to remove the workspace SSH key this machine registered and to revoke this terminal's device token; a key it refuses to remove, or one this machine cannot read, makes the uninstall exit 1 naming what may still be registered. The account's other keys and devices stay.",
3635
- "Everything also offers what else Mend put on the Docker host: the images it pulled and built (the bundle's, the workspace images, the workspaces' Docker service and network guard), with the space they take, and the user-namespace sysctl file setup wrote, putting back the setting it replaced. A sysctl file written by hand stays, with the command that removes it. Docker's build cache is shared by every build on the daemon, so it gets its own question, and stays under --yes. The CLI itself stays: npm uninstall -g @sealant/mend removes it. The last line names whatever is still here.",
3644
+ "Everything also offers what else Mend put on the Docker host: the images it pulled and built (the bundle's, the workspace images, the workspaces' Docker service and network guard), with the space they take, and the user-namespace sysctl file setup wrote, putting back the setting it replaced. A sysctl file written by hand stays, with the command that removes it. Docker's build cache is shared by every build on the daemon, so it gets its own question, and stays under --yes. When the uninstall stops before these, it says each one was not reached, and the next run removes them. The CLI itself stays: npm uninstall -g @sealant/mend removes it. The last line names whatever is still here.",
3636
3645
  "Nothing else under the configuration directory is touched; a host-run store or keys root is listed and left in place. With no configuration here, Docker volumes carrying Mend's installation label and no anchor are what an earlier install left: the server scope lists and removes them."
3637
3646
  ],
3638
3647
  options: [
@@ -4104,153 +4113,115 @@ var doctorBundleCommand = async (args, deps) => {
4104
4113
  };
4105
4114
 
4106
4115
  // src/doctor.ts
4116
+ import { spawnSync as spawnSync4 } from "node:child_process";
4107
4117
  import * as fs9 from "node:fs";
4108
4118
  import * as path9 from "node:path";
4109
4119
 
4110
4120
  // src/docker-shutdown.ts
4111
4121
  import { spawnSync as spawnSync3 } from "node:child_process";
4112
4122
  import * as fs8 from "node:fs";
4113
- import * as os5 from "node:os";
4114
4123
  import * as path8 from "node:path";
4115
- var DOCKER_CAPTURE_STOP_GRACE_SECONDS = 3600;
4116
- var DOCKERD_DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 15;
4117
- var flagValue = (argv, name) => {
4118
- for (let index = 0; index < argv.length; index += 1) {
4119
- const arg = argv[index] ?? "";
4120
- if (arg.startsWith(`${name}=`)) return arg.slice(name.length + 1);
4121
- if (arg === name) return argv[index + 1] ?? "";
4122
- }
4123
- return null;
4124
- };
4125
- var seconds = (value) => {
4126
- if (typeof value === "number" && Number.isInteger(value) && value >= 0) return value;
4127
- if (typeof value === "string" && /^\d+$/.test(value.trim())) return Number(value.trim());
4128
- return null;
4129
- };
4124
+ var WORKSPACE_STOP_TIMEOUT_SECONDS = 60;
4125
+ var DOCKER_DEFAULT_STOP_TIMEOUT_SECONDS = 10;
4126
+ var DOCKERD_SHUTDOWN_GRACE_SECONDS = 5;
4127
+ var SYSTEMD_DEFAULT_STOP_SECONDS = 90;
4130
4128
  var daemonKindOf = (info) => {
4131
4129
  if (/docker desktop/i.test(info.operatingSystem)) return "desktop";
4132
4130
  if (/orbstack/i.test(info.operatingSystem)) return "orbstack";
4133
4131
  if (info.securityOptions.some((option) => option.includes("name=rootless"))) return "rootless";
4134
4132
  return "dockerd";
4135
4133
  };
4136
- var defaultConfigPath = (facts, daemon) => {
4137
- switch (daemon) {
4138
- case "desktop":
4139
- return path8.join(facts.home, ".docker", "daemon.json");
4140
- case "orbstack":
4141
- return path8.join(facts.home, ".orbstack", "config", "docker.json");
4142
- case "rootless":
4143
- return path8.join(
4144
- facts.xdgConfigHome ?? path8.join(facts.home, ".config"),
4145
- "docker",
4146
- "daemon.json"
4147
- );
4148
- case "dockerd":
4149
- return "/etc/docker/daemon.json";
4134
+ var stopLimitOf = (facts, daemon) => {
4135
+ if (daemon === "desktop" || daemon === "orbstack") {
4136
+ return { kind: "none", why: "no systemd unit runs this daemon" };
4150
4137
  }
4138
+ const unit = facts.unit;
4139
+ if (unit === null) return { kind: "none", why: "no systemd unit observed" };
4140
+ if (unit.activeState !== "active") {
4141
+ return { kind: "none", why: `${unit.name} is ${unit.activeState}` };
4142
+ }
4143
+ if (daemon === "dockerd" && facts.dockerdPid !== null && unit.mainPid !== facts.dockerdPid) {
4144
+ return { kind: "none", why: `${unit.name} is not the dockerd docker talks to` };
4145
+ }
4146
+ return { kind: "observed", unit: unit.name, seconds: unit.timeoutStopSeconds };
4151
4147
  };
4152
- var readShutdownTimeout = (facts) => {
4148
+ var readDockerStop = (facts, expected = null) => {
4153
4149
  if (facts.info === null) return { kind: "unknown", why: "docker info did not answer" };
4154
- const daemon = daemonKindOf(facts.info);
4155
- const managed = daemon === "desktop" || daemon === "orbstack";
4156
- const argv = managed ? null : facts.dockerdArgv;
4157
- const unresolved = facts.dockerdUnresolved ?? null;
4158
- if (argv === null && !managed && unresolved !== null) return { kind: "unknown", why: unresolved };
4159
- const configPath = (argv === null ? null : flagValue(argv, "--config-file")) ?? defaultConfigPath(facts, daemon);
4160
- if (argv !== null) {
4161
- const flag = flagValue(argv, "--shutdown-timeout");
4162
- if (flag !== null) {
4163
- const value = seconds(flag);
4164
- return value === null ? { kind: "unknown", why: `dockerd --shutdown-timeout ${flag} unreadable` } : {
4165
- kind: "observed",
4166
- seconds: value,
4167
- source: "dockerd --shutdown-timeout",
4168
- daemon,
4169
- configPath,
4170
- fromFlag: true
4171
- };
4172
- }
4173
- }
4174
- const file = facts.readFile(configPath);
4175
- if (file.kind === "unreadable") return { kind: "unknown", why: `${configPath} unreadable` };
4176
- if (file.kind === "read") {
4177
- let parsed;
4178
- try {
4179
- parsed = JSON.parse(file.text);
4180
- } catch {
4181
- return { kind: "unknown", why: `${configPath} is not JSON` };
4182
- }
4183
- const configured = typeof parsed === "object" && parsed !== null && "shutdown-timeout" in parsed ? parsed["shutdown-timeout"] : void 0;
4184
- if (configured !== void 0) {
4185
- const value = seconds(configured);
4186
- return value === null ? { kind: "unknown", why: `shutdown-timeout in ${configPath} unreadable` } : {
4187
- kind: "observed",
4188
- seconds: value,
4189
- source: configPath,
4190
- daemon,
4191
- configPath,
4192
- fromFlag: false
4193
- };
4150
+ if (facts.info.liveRestore) return { kind: "live-restore" };
4151
+ if (facts.containers === null)
4152
+ return { kind: "unknown", why: "its containers could not be read" };
4153
+ let waitSeconds = expected ?? 0;
4154
+ let longest = expected === null ? null : { kind: "workspaces" };
4155
+ for (const container of facts.containers) {
4156
+ const seconds = container.stopTimeout ?? DOCKER_DEFAULT_STOP_TIMEOUT_SECONDS;
4157
+ if (seconds > waitSeconds) {
4158
+ waitSeconds = seconds;
4159
+ longest = { kind: "container", name: container.name };
4194
4160
  }
4195
4161
  }
4196
- if (argv === null && !managed) {
4197
- return {
4198
- kind: "unknown",
4199
- why: `no dockerd process observed here \xB7 not set in ${configPath}`
4200
- };
4201
- }
4202
4162
  return {
4203
4163
  kind: "observed",
4204
- seconds: DOCKERD_DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,
4205
- source: `dockerd default \xB7 not set in ${configPath}`,
4206
- daemon,
4207
- configPath,
4208
- fromFlag: false
4164
+ waitSeconds,
4165
+ longest,
4166
+ limit: stopLimitOf(facts, daemonKindOf(facts.info))
4209
4167
  };
4210
4168
  };
4211
- var restartWords = (daemon) => {
4212
- switch (daemon) {
4213
- case "desktop":
4214
- return "restart Docker Desktop";
4215
- case "orbstack":
4216
- return "restart OrbStack";
4217
- case "rootless":
4218
- return "systemctl --user restart docker";
4219
- case "dockerd":
4220
- return "restart dockerd";
4221
- }
4222
- };
4223
- var raiseShutdownTimeoutWords = (reading, grace) => reading.fromFlag ? `raise dockerd --shutdown-timeout to ${grace}, then ${restartWords(reading.daemon)}` : `set "shutdown-timeout": ${grace} in ${reading.configPath}, then ${restartWords(reading.daemon)}`;
4224
- var dockerShutdownCheck = (reading, grace = DOCKER_CAPTURE_STOP_GRACE_SECONDS) => {
4169
+ var limitSeconds = (limit) => limit.kind === "observed" ? limit.seconds : SYSTEMD_DEFAULT_STOP_SECONDS;
4170
+ var outlasts = (reading) => {
4171
+ const limit = limitSeconds(reading.limit);
4172
+ return limit !== null && reading.waitSeconds + DOCKERD_SHUTDOWN_GRACE_SECONDS >= limit;
4173
+ };
4174
+ var whose = (reading) => {
4175
+ if (reading.longest === null) return "no container running";
4176
+ if (reading.longest.kind === "workspaces") return "a workspace's stop timeout";
4177
+ return `${reading.longest.name}'s stop timeout`;
4178
+ };
4179
+ var stopWords = (reading) => reading.longest === null ? "no container running" : `a Docker stop waits up to ${reading.waitSeconds} s \xB7 ${whose(reading)}`;
4180
+ var limitWords = (limit, ok) => {
4181
+ if (limit.kind === "none")
4182
+ return `${limit.why} (systemd's default is ${SYSTEMD_DEFAULT_STOP_SECONDS} s)`;
4183
+ if (limit.seconds === null) return `systemd waits for ${limit.unit} without a limit`;
4184
+ return ok ? `systemd allows ${limit.unit} ${limit.seconds} s` : `systemd kills ${limit.unit} after ${limit.seconds} s, and Docker's next start waits for what it left running`;
4185
+ };
4186
+ var isWorkspace = (name) => name.startsWith("sealant-");
4187
+ var fixWords = (reading) => {
4188
+ const longest = reading.longest;
4189
+ if (longest !== null && longest.kind === "container" && reading.waitSeconds > WORKSPACE_STOP_TIMEOUT_SECONDS) {
4190
+ return isWorkspace(longest.name) ? "stop that session (mend sessions, then mend stop <session>) before you restart or upgrade Docker" : `docker stop ${longest.name} before you restart or upgrade Docker`;
4191
+ }
4192
+ const room = reading.waitSeconds + DOCKERD_SHUTDOWN_GRACE_SECONDS + 30;
4193
+ return reading.limit.kind === "observed" ? `sudo systemctl edit ${reading.limit.unit.replace(" (user)", "")} and set [Service] TimeoutStopSec=${room}` : "stop sessions before you restart, upgrade or quit Docker";
4194
+ };
4195
+ var dockerStopCheck = (reading) => {
4225
4196
  if (reading.kind === "unknown") {
4226
4197
  return {
4227
4198
  label: "docker",
4228
4199
  state: "todo",
4229
- detail: `shutdown-timeout not observed \xB7 ${reading.why}`,
4200
+ detail: `Docker stop not observed \xB7 ${reading.why}`,
4230
4201
  fix: null
4231
4202
  };
4232
4203
  }
4233
- if (reading.seconds >= grace) {
4204
+ if (reading.kind === "live-restore") {
4234
4205
  return {
4235
4206
  label: "docker",
4236
4207
  state: "ok",
4237
- detail: `shutdown-timeout ${reading.seconds} s \xB7 ${reading.source} \xB7 covers the ${grace} s capture grace`,
4208
+ detail: "live-restore on \xB7 a Docker restart leaves sessions running",
4238
4209
  fix: null
4239
4210
  };
4240
4211
  }
4212
+ const ok = !outlasts(reading);
4241
4213
  return {
4242
4214
  label: "docker",
4243
- state: "todo",
4244
- detail: `shutdown-timeout ${reading.seconds} s \xB7 ${reading.source} \xB7 below the ${grace} s capture grace`,
4245
- fix: raiseShutdownTimeoutWords(reading, grace)
4215
+ state: ok ? "ok" : "todo",
4216
+ detail: `${stopWords(reading)} \xB7 ${limitWords(reading.limit, ok)}`,
4217
+ fix: ok ? null : fixWords(reading)
4246
4218
  };
4247
4219
  };
4248
- var dockerShutdownSetupLine = (reading, grace = DOCKER_CAPTURE_STOP_GRACE_SECONDS) => {
4249
- if (reading.kind === "unknown") {
4250
- return `Docker shutdown-timeout not observed (${reading.why}); a daemon shutdown below ${grace} s kills capture workspaces before they save. See docs/SELF-HOSTING.md.`;
4251
- }
4252
- if (reading.seconds >= grace) return null;
4253
- return `Docker shutdown-timeout is ${reading.seconds} s (${reading.source}), below the ${grace} s capture grace: a host restart or daemon stop kills capture workspaces after ${reading.seconds} s, before they save. To raise it: ${raiseShutdownTimeoutWords(reading, grace)}.`;
4220
+ var dockerStopSetupLine = (reading) => {
4221
+ if (reading.kind === "live-restore") return null;
4222
+ if (reading.kind === "unknown") return null;
4223
+ if (!outlasts(reading)) return null;
4224
+ return `A Docker stop waits up to ${reading.waitSeconds} s (${whose(reading)}), but ${limitWords(reading.limit, false)}: a restart or upgrade of Docker with a live session leaves Docker down until that workspace ends. To avoid it: ${fixWords(reading)}.`;
4254
4225
  };
4255
4226
  var parseDockerInfo = (stdout) => {
4256
4227
  let parsed;
@@ -4265,15 +4236,52 @@ var parseDockerInfo = (stdout) => {
4265
4236
  const options = "SecurityOptions" in parsed ? parsed.SecurityOptions : [];
4266
4237
  return {
4267
4238
  operatingSystem,
4268
- securityOptions: Array.isArray(options) ? options.filter((option) => typeof option === "string") : []
4239
+ securityOptions: Array.isArray(options) ? options.filter((option) => typeof option === "string") : [],
4240
+ liveRestore: "LiveRestoreEnabled" in parsed && parsed.LiveRestoreEnabled === true
4269
4241
  };
4270
4242
  };
4271
- var readHostFile = (file) => {
4272
- try {
4273
- return { kind: "read", text: fs8.readFileSync(file, "utf8") };
4274
- } catch (cause) {
4275
- return cause instanceof Error && "code" in cause && cause.code === "ENOENT" ? { kind: "absent" } : { kind: "unreadable" };
4243
+ var parseContainerStopTimeouts = (stdout) => stdout.split("\n").map((line) => line.trim()).filter((line) => line !== "").map((line) => {
4244
+ const bar = line.lastIndexOf("|");
4245
+ const name = (bar < 0 ? line : line.slice(0, bar)).replace(/^\//, "");
4246
+ const value = bar < 0 ? "" : line.slice(bar + 1).trim();
4247
+ return { name, stopTimeout: /^\d+$/.test(value) ? Number(value) : null };
4248
+ });
4249
+ var TIMESPAN_UNITS = {
4250
+ us: 1e-6,
4251
+ ms: 1e-3,
4252
+ s: 1,
4253
+ sec: 1,
4254
+ m: 60,
4255
+ min: 60,
4256
+ h: 3600,
4257
+ hr: 3600,
4258
+ d: 86400,
4259
+ w: 604800
4260
+ };
4261
+ var parseSystemdTimespan = (text) => {
4262
+ const value = text.trim();
4263
+ if (value === "infinity") return null;
4264
+ if (value === "") return void 0;
4265
+ let total = 0;
4266
+ for (const part of value.split(/\s+/)) {
4267
+ const match = /^(\d+(?:\.\d+)?)([a-z]*)$/.exec(part);
4268
+ const unit = match?.[2] === "" ? "s" : match?.[2];
4269
+ const factor = unit === void 0 ? void 0 : TIMESPAN_UNITS[unit];
4270
+ if (match === null || factor === void 0) return void 0;
4271
+ total += Number(match[1]) * factor;
4276
4272
  }
4273
+ return Math.round(total);
4274
+ };
4275
+ var parseDaemonUnit = (name, stdout) => {
4276
+ const fields = /* @__PURE__ */ new Map();
4277
+ for (const line of stdout.split("\n")) {
4278
+ const equals = line.indexOf("=");
4279
+ if (equals > 0) fields.set(line.slice(0, equals), line.slice(equals + 1));
4280
+ }
4281
+ const activeState = fields.get("ActiveState");
4282
+ const timeout = parseSystemdTimespan(fields.get("TimeoutStopUSec") ?? "");
4283
+ if (activeState === void 0 || timeout === void 0) return null;
4284
+ return { name, activeState, mainPid: fields.get("MainPID") ?? "", timeoutStopSeconds: timeout };
4277
4285
  };
4278
4286
  var hostProcView = {
4279
4287
  list: (dir) => {
@@ -4389,65 +4397,134 @@ var observeDockerd = (proc, host) => {
4389
4397
  why: only === void 0 ? `${seen} \xB7 none observed serving ${socket}` : `${seen} \xB7 could not tell which serves ${socket}`
4390
4398
  };
4391
4399
  };
4392
- var hostDockerEndpoint = () => {
4393
- const fromEnv = process.env["DOCKER_HOST"];
4400
+ var hostDockerEndpoint = (context = null) => {
4401
+ const fromEnv = context === null ? process.env["DOCKER_HOST"] : void 0;
4394
4402
  if (fromEnv !== void 0 && fromEnv.trim() !== "") return fromEnv.trim();
4395
- const context = spawnSync3(
4403
+ const inspected = spawnSync3(
4396
4404
  "docker",
4397
- ["context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
4405
+ [
4406
+ "context",
4407
+ "inspect",
4408
+ ...context === null ? [] : [context],
4409
+ "--format",
4410
+ "{{.Endpoints.docker.Host}}"
4411
+ ],
4398
4412
  {
4399
4413
  encoding: "utf8",
4400
4414
  timeout: 3e3,
4401
4415
  stdio: ["ignore", "pipe", "ignore"]
4402
4416
  }
4403
4417
  );
4404
- const endpoint = context.status === 0 ? context.stdout.trim() : "";
4418
+ const endpoint = inspected.status === 0 ? inspected.stdout.trim() : "";
4405
4419
  return endpoint === "" ? DOCKER_DEFAULT_HOST : endpoint;
4406
4420
  };
4407
- var dockerdFactsOf = (observation) => {
4408
- switch (observation.kind) {
4409
- case "observed":
4410
- return { dockerdArgv: observation.argv, dockerdUnresolved: null };
4411
- case "none":
4412
- return { dockerdArgv: null, dockerdUnresolved: null };
4413
- case "unresolved":
4414
- return { dockerdArgv: null, dockerdUnresolved: observation.why };
4415
- }
4416
- };
4417
- var hostDockerDaemonFacts = (infoStdout) => ({
4418
- info: infoStdout === null ? null : parseDockerInfo(infoStdout),
4419
- ...dockerdFactsOf(observeDockerd(hostProcView, hostDockerEndpoint())),
4420
- readFile: readHostFile,
4421
- home: os5.homedir(),
4422
- xdgConfigHome: process.env["XDG_CONFIG_HOME"] ?? null
4423
- });
4424
- var observeHostShutdownTimeout = () => {
4425
- const info = spawnSync3("docker", ["info", "--format", "{{json .}}"], {
4421
+ var runBounded = (command, args) => {
4422
+ const result = spawnSync3(command, [...args], {
4426
4423
  encoding: "utf8",
4427
4424
  timeout: 3e3,
4428
4425
  stdio: ["ignore", "pipe", "ignore"]
4429
4426
  });
4430
- return readShutdownTimeout(hostDockerDaemonFacts(info.status === 0 ? info.stdout : null));
4427
+ return result.status === 0 ? result.stdout : null;
4428
+ };
4429
+ var hostDockerDaemonFacts = (infoStdout, context = null) => {
4430
+ const info = infoStdout === null ? null : parseDockerInfo(infoStdout);
4431
+ const contextArgs = context === null ? [] : ["--context", context];
4432
+ const ids = info === null ? null : runBounded("docker", [...contextArgs, "ps", "-q"]);
4433
+ const idList = ids?.split("\n").map((id) => id.trim()).filter((id) => id !== "") ?? [];
4434
+ const inspected = ids === null ? null : idList.length === 0 ? "" : runBounded("docker", [
4435
+ ...contextArgs,
4436
+ "inspect",
4437
+ "--format",
4438
+ "{{.Name}}|{{json .Config.StopTimeout}}",
4439
+ ...idList
4440
+ ]);
4441
+ const daemon = info === null ? null : daemonKindOf(info);
4442
+ const unitArgs = [
4443
+ "show",
4444
+ "docker.service",
4445
+ "-p",
4446
+ "ActiveState",
4447
+ "-p",
4448
+ "MainPID",
4449
+ "-p",
4450
+ "TimeoutStopUSec"
4451
+ ];
4452
+ const unitText = daemon === "dockerd" ? runBounded("systemctl", unitArgs) : daemon === "rootless" ? runBounded("systemctl", ["--user", ...unitArgs]) : null;
4453
+ const observed = observeDockerd(hostProcView, hostDockerEndpoint(context));
4454
+ return {
4455
+ info,
4456
+ dockerdPid: observed.kind === "observed" ? observed.pid : null,
4457
+ containers: inspected === null ? null : parseContainerStopTimeouts(inspected),
4458
+ unit: unitText === null ? null : parseDaemonUnit(
4459
+ daemon === "rootless" ? "docker.service (user)" : "docker.service",
4460
+ unitText
4461
+ )
4462
+ };
4463
+ };
4464
+ var observeHostDockerStop = (context = null) => {
4465
+ const info = spawnSync3(
4466
+ "docker",
4467
+ [...context === null ? [] : ["--context", context], "info", "--format", "{{json .}}"],
4468
+ {
4469
+ encoding: "utf8",
4470
+ timeout: 3e3,
4471
+ stdio: ["ignore", "pipe", "ignore"]
4472
+ }
4473
+ );
4474
+ return readDockerStop(hostDockerDaemonFacts(info.status === 0 ? info.stdout : null, context));
4431
4475
  };
4432
4476
 
4433
4477
  // src/doctor.ts
4434
4478
  var TIMEOUT_MS = 3e3;
4479
+ var pmsetValue = (output, name) => {
4480
+ const match = new RegExp(`^\\s*${name}\\s+(\\d+)`, "m").exec(output);
4481
+ return match?.[1] === void 0 ? null : Number(match[1]);
4482
+ };
4483
+ var macSleepCheck = (pmset) => {
4484
+ const sleepMinutes = pmsetValue(pmset, "sleep");
4485
+ if (sleepMinutes === null || sleepMinutes === 0) return null;
4486
+ const wakeForNetwork = pmsetValue(pmset, "womp");
4487
+ return {
4488
+ label: "sleep",
4489
+ state: "todo",
4490
+ detail: `this Mac sleeps after ${sleepMinutes} min idle, and the Docker VM pauses while it sleeps: builds stall, sessions drop, its clock drifts`,
4491
+ fix: `sudo pmset -a sleep 0 disksleep 0${wakeForNetwork === 0 ? " womp 1" : ""} (System Settings \u2192 Energy \u2192 Prevent automatic sleeping when the display is off${wakeForNetwork === 0 ? ", and Wake for network access" : ""})`
4492
+ };
4493
+ };
4494
+ var readMacPowerSettings = () => {
4495
+ const read = spawnSync4("pmset", ["-g"], { encoding: "utf8", timeout: TIMEOUT_MS });
4496
+ return read.status === 0 ? read.stdout : null;
4497
+ };
4435
4498
  var MARKS = { ok: "\u2713", todo: "\u25CB", failed: "\u2717" };
4436
4499
  var LABEL_WIDTH = 11;
4437
4500
  var day = (at) => at.toISOString().slice(0, 10);
4438
4501
  var formatCheck = (check, paint7 = (_state, mark) => mark) => `${paint7(check.state, MARKS[check.state])} ${check.label.padEnd(LABEL_WIDTH)} ${check.detail}${check.fix === null ? "" : ` \u2192 ${check.fix}`}`;
4439
4502
  var getJson = async (config, route) => {
4440
4503
  try {
4504
+ const sent = Date.now();
4441
4505
  const response = await fetch(`${config.url}/api${route}`, {
4442
4506
  headers: config.token === null ? {} : { authorization: `Bearer ${config.token}` },
4443
4507
  signal: AbortSignal.timeout(TIMEOUT_MS)
4444
4508
  });
4445
- if (!response.ok) return { value: null, status: response.status };
4446
- return { value: await response.json(), status: response.status };
4509
+ const date = Date.parse(response.headers.get("date") ?? "");
4510
+ const clockSkewMs = Number.isNaN(date) ? null : date - (sent + Date.now()) / 2;
4511
+ if (!response.ok) return { value: null, status: response.status, clockSkewMs };
4512
+ return { value: await response.json(), status: response.status, clockSkewMs };
4447
4513
  } catch {
4448
- return { value: null, status: null };
4514
+ return { value: null, status: null, clockSkewMs: null };
4449
4515
  }
4450
4516
  };
4517
+ var CLOCK_SKEW_FINDING_MS = 2 * 6e4;
4518
+ var clockCheck = (clockSkewMs) => {
4519
+ if (Math.abs(clockSkewMs) < CLOCK_SKEW_FINDING_MS) return null;
4520
+ const minutes = Math.round(Math.abs(clockSkewMs) / 6e4);
4521
+ return {
4522
+ label: "clock",
4523
+ state: "todo",
4524
+ detail: `this server's clock is ${minutes} min ${clockSkewMs < 0 ? "behind" : "ahead of"} this machine's`,
4525
+ fix: "if the server runs in OrbStack or Docker Desktop, restart it; otherwise check NTP on both machines (timedatectl, or sntp on a Mac)"
4526
+ };
4527
+ };
4451
4528
  var exposureCheck = (exposure) => {
4452
4529
  const beyondMachine = exposure.declared !== "loopback" && exposure.originOnMachine !== true;
4453
4530
  const gateOpen = beyondMachine ? exposure.gateOpen : 0;
@@ -4462,7 +4539,7 @@ var exposureCheck = (exposure) => {
4462
4539
  label: "exposure",
4463
4540
  state: plainBeyondMachine ? "todo" : "ok",
4464
4541
  detail: facts,
4465
- fix: plainBeyondMachine ? "serve it over https and set APP_URL to that origin" : gateOpen === 0 ? null : "mend operator exposure"
4542
+ fix: plainBeyondMachine ? "serve it over https: on the server's machine, mend server setup --edge <domain>, or mend server setup --url https://<origin> behind HTTPS you run" : gateOpen === 0 ? null : "mend operator exposure"
4466
4543
  };
4467
4544
  };
4468
4545
  var userNamespacesCheck = (observed) => observed.allowed ? {
@@ -4500,16 +4577,15 @@ var identityOf = (account) => {
4500
4577
  }
4501
4578
  return null;
4502
4579
  };
4503
- var unreachedServer = async (config, probes) => {
4504
- const local = probes.localServerUrl === void 0 ? null : await probes.localServerUrl();
4505
- if (local !== null && local !== config.url) {
4506
- const there = await getJson({ url: local, token: null }, "/health");
4580
+ var unreachedServer = async (config, local) => {
4581
+ if (local !== null && local.url !== config.url) {
4582
+ const there = await getJson({ url: local.url, token: null }, "/health");
4507
4583
  if (there.value !== null) {
4508
4584
  return {
4509
4585
  label: "server",
4510
4586
  state: "failed",
4511
- detail: `cannot reach ${config.url} \xB7 the Mend server on this machine answers at ${local}, and this CLI points at the old URL`,
4512
- fix: `mend login --url ${local}`
4587
+ detail: `cannot reach ${config.url} \xB7 the Mend server on this machine answers at ${local.url}, and this CLI points at the old URL`,
4588
+ fix: `mend login --url ${local.url}`
4513
4589
  };
4514
4590
  }
4515
4591
  }
@@ -4520,17 +4596,42 @@ var unreachedServer = async (config, probes) => {
4520
4596
  fix: "start the Mend server (mend server start on its machine), or, if its URL changed, mend login --url <its URL>"
4521
4597
  };
4522
4598
  };
4599
+ var isLoopbackUrl = (url) => {
4600
+ try {
4601
+ const host = new URL(url).hostname;
4602
+ return host === "localhost" || host === "[::1]" || host.startsWith("127.");
4603
+ } catch {
4604
+ return false;
4605
+ }
4606
+ };
4607
+ var answeredServer = async (config, health, local) => {
4608
+ const ok = {
4609
+ label: "server",
4610
+ state: "ok",
4611
+ detail: `${config.url} \xB7 mend ${health.version}`,
4612
+ fix: null
4613
+ };
4614
+ if (local === null || local.url === config.url || !isLoopbackUrl(config.url)) return ok;
4615
+ const same = health.instance === void 0 ? health.version === local.version : health.instance === local.instance;
4616
+ if (same) return ok;
4617
+ const there = await getJson({ url: local.url, token: null }, "/health");
4618
+ if (there.value === null) return ok;
4619
+ return {
4620
+ label: "server",
4621
+ state: "todo",
4622
+ detail: `${config.url} \xB7 mend ${health.version} \xB7 not the server installed on this machine, which answers at ${local.url} (mend ${there.value.version})`,
4623
+ fix: `mend login --url ${local.url}`
4624
+ };
4625
+ };
4523
4626
  var runChecks = async (config, probes) => {
4524
4627
  const checks = [];
4525
4628
  const health = await getJson(config, "/health");
4629
+ const local = probes.localServer === void 0 ? null : await probes.localServer();
4526
4630
  checks.push(
4527
- health.value === null ? await unreachedServer(config, probes) : {
4528
- label: "server",
4529
- state: "ok",
4530
- detail: `${config.url} \xB7 mend ${health.value.version}`,
4531
- fix: null
4532
- }
4631
+ health.value === null ? await unreachedServer(config, local) : await answeredServer(config, health.value, local)
4533
4632
  );
4633
+ const clock2 = health.value === null || health.clockSkewMs === null ? null : clockCheck(health.clockSkewMs);
4634
+ if (clock2 !== null) checks.push(clock2);
4534
4635
  const projects = health.value !== null && config.token !== null ? await getJson(config, "/projects") : null;
4535
4636
  if (health.value === null) checks.push(notChecked("signed in"));
4536
4637
  else if (config.token === null) {
@@ -4674,9 +4775,12 @@ var runChecks = async (config, probes) => {
4674
4775
  checks.push(exposure === void 0 ? notChecked("exposure") : exposureCheck(exposure));
4675
4776
  const userNamespaces = machine === null || machine.value === null ? void 0 : machine.value.userNamespaces;
4676
4777
  if (userNamespaces !== void 0) checks.push(userNamespacesCheck(userNamespaces));
4677
- if (probes.dockerShutdown !== void 0 && probes.onPath("docker")) {
4678
- checks.push(dockerShutdownCheck(probes.dockerShutdown()));
4778
+ if (probes.dockerStop !== void 0 && probes.onPath("docker")) {
4779
+ checks.push(dockerStopCheck(probes.dockerStop(local?.dockerContext ?? null)));
4679
4780
  }
4781
+ const pmset = local === null || probes.macPowerSettings === void 0 ? null : probes.macPowerSettings();
4782
+ const sleep3 = pmset === null ? null : macSleepCheck(pmset);
4783
+ if (sleep3 !== null) checks.push(sleep3);
4680
4784
  return checks;
4681
4785
  };
4682
4786
  var onPath = (command) => {
@@ -4695,13 +4799,14 @@ var paintMark = (state, mark) => {
4695
4799
  const code = state === "ok" ? "32" : state === "todo" ? "33" : "31";
4696
4800
  return `\x1B[${code}m${mark}\x1B[0m`;
4697
4801
  };
4698
- var doctorCommand = async (config, localCredential2, claudeGrant2, localServerUrl) => {
4802
+ var doctorCommand = async (config, localCredential2, claudeGrant2, localServer) => {
4699
4803
  const checks = await runChecks(config, {
4700
4804
  localCredential: localCredential2,
4701
4805
  claudeGrant: claudeGrant2,
4702
4806
  onPath,
4703
- dockerShutdown: observeHostShutdownTimeout,
4704
- ...localServerUrl === void 0 ? {} : { localServerUrl }
4807
+ dockerStop: observeHostDockerStop,
4808
+ ...localServer === void 0 ? {} : { localServer },
4809
+ ...process.platform === "darwin" ? { macPowerSettings: readMacPowerSettings } : {}
4705
4810
  });
4706
4811
  for (const check of checks) {
4707
4812
  process.stdout.write(`${redactCredentials(formatCheck(check, paintMark))}
@@ -4753,44 +4858,44 @@ var DOTFILE_CANDIDATES = [
4753
4858
  }
4754
4859
  ];
4755
4860
  var MAX_FILE_BYTES = 1024 * 1024;
4756
- var statFile = (home, relative5) => {
4861
+ var statFile = (home, relative6) => {
4757
4862
  try {
4758
- const stat = fs10.statSync(path10.join(home, relative5));
4863
+ const stat = fs10.statSync(path10.join(home, relative6));
4759
4864
  return stat.isFile() ? stat : null;
4760
4865
  } catch {
4761
4866
  return null;
4762
4867
  }
4763
4868
  };
4764
4869
  var scanDotfileCandidates = (home) => DOTFILE_CANDIDATES.flatMap(
4765
- ({ group, paths }) => paths.flatMap((relative5) => {
4766
- const stat = statFile(home, relative5);
4767
- return stat === null ? [] : [{ path: relative5, group, bytes: stat.size }];
4870
+ ({ group, paths }) => paths.flatMap((relative6) => {
4871
+ const stat = statFile(home, relative6);
4872
+ return stat === null ? [] : [{ path: relative6, group, bytes: stat.size }];
4768
4873
  })
4769
4874
  );
4770
4875
  var homeRelativePath = (home, requested) => {
4771
- const relative5 = path10.relative(home, path10.resolve(home, requested));
4772
- const outside = relative5 === "" || relative5 === ".." || relative5.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative5);
4773
- return outside ? null : relative5.split(path10.sep).join("/");
4876
+ const relative6 = path10.relative(home, path10.resolve(home, requested));
4877
+ const outside = relative6 === "" || relative6 === ".." || relative6.startsWith(`..${path10.sep}`) || path10.isAbsolute(relative6);
4878
+ return outside ? null : relative6.split(path10.sep).join("/");
4774
4879
  };
4775
4880
  var readSyncFiles = (home, paths_) => {
4776
4881
  const files = [];
4777
4882
  for (const requested of paths_) {
4778
- const relative5 = homeRelativePath(home, requested);
4779
- if (relative5 === null) {
4883
+ const relative6 = homeRelativePath(home, requested);
4884
+ if (relative6 === null) {
4780
4885
  return {
4781
4886
  error: `${requested} is not under ${home} \u2014 only files in your home directory sync`
4782
4887
  };
4783
4888
  }
4784
- const stat = statFile(home, relative5);
4889
+ const stat = statFile(home, relative6);
4785
4890
  if (stat === null) {
4786
- return { error: `${relative5} is not a file under ${home}` };
4891
+ return { error: `${relative6} is not a file under ${home}` };
4787
4892
  }
4788
4893
  if (stat.size > MAX_FILE_BYTES) {
4789
- return { error: `${relative5} is over 1MB \u2014 dotfiles are text; trim the selection` };
4894
+ return { error: `${relative6} is over 1MB \u2014 dotfiles are text; trim the selection` };
4790
4895
  }
4791
4896
  files.push({
4792
- path: relative5,
4793
- contentsBase64: fs10.readFileSync(path10.join(home, relative5)).toString("base64"),
4897
+ path: relative6,
4898
+ contentsBase64: fs10.readFileSync(path10.join(home, relative6)).toString("base64"),
4794
4899
  // eslint-disable-next-line no-bitwise -- permission bits are the point
4795
4900
  mode: (stat.mode & 511).toString(8)
4796
4901
  });
@@ -4953,9 +5058,9 @@ var useHttp1 = () => {
4953
5058
  };
4954
5059
 
4955
5060
  // src/landing.ts
4956
- import { spawnSync as spawnSync4 } from "node:child_process";
5061
+ import { spawnSync as spawnSync5 } from "node:child_process";
4957
5062
  import * as fs11 from "node:fs";
4958
- import * as os6 from "node:os";
5063
+ import * as os5 from "node:os";
4959
5064
  import * as path11 from "node:path";
4960
5065
  var paint = (code) => (text) => process.stdout.isTTY === true ? `[${code}m${text}[0m` : text;
4961
5066
  var dim = paint("2");
@@ -5176,7 +5281,7 @@ var landCommand = async (api2, args) => {
5176
5281
  if (!landingSucceeded(report)) process.exitCode = 1;
5177
5282
  };
5178
5283
  var git = (cwd, args) => {
5179
- const result = spawnSync4("git", args, { cwd, encoding: "utf8" });
5284
+ const result = spawnSync5("git", args, { cwd, encoding: "utf8" });
5180
5285
  return {
5181
5286
  status: result.status ?? 1,
5182
5287
  stdout: result.stdout ?? "",
@@ -5252,7 +5357,7 @@ var fetchBundle = (cwd, bundle, into = bundle.branch) => {
5252
5357
  recordAt(previous);
5253
5358
  return { _tag: "unchanged", branch: into, here: previous, tip: bundle.tip };
5254
5359
  }
5255
- const dir = fs11.mkdtempSync(path11.join(os6.tmpdir(), "mend-pull-"));
5360
+ const dir = fs11.mkdtempSync(path11.join(os5.tmpdir(), "mend-pull-"));
5256
5361
  try {
5257
5362
  const file = path11.join(dir, "change.bundle");
5258
5363
  fs11.writeFileSync(file, bundle.bytes, { mode: 384 });
@@ -5494,7 +5599,7 @@ var followStart = async (options) => {
5494
5599
 
5495
5600
  // src/login.ts
5496
5601
  import { spawn as spawn2 } from "node:child_process";
5497
- import * as os7 from "node:os";
5602
+ import * as os6 from "node:os";
5498
5603
 
5499
5604
  // src/pair.ts
5500
5605
  var paint2 = (code) => (text) => process.stdout.isTTY === true ? `\x1B[${code}m${text}\x1B[0m` : text;
@@ -5566,7 +5671,15 @@ var parseCliAuthStart = (json2) => {
5566
5671
  if (typeof deviceCode !== "string" || typeof code !== "string" || typeof verifyPath !== "string" || typeof expiresAt !== "string" || typeof intervalSeconds !== "number") {
5567
5672
  return null;
5568
5673
  }
5569
- return { deviceCode, code, verifyPath, expiresAt, intervalSeconds };
5674
+ const expiresIn = "expiresIn" in json2 ? json2.expiresIn : void 0;
5675
+ return {
5676
+ deviceCode,
5677
+ code,
5678
+ verifyPath,
5679
+ expiresAt,
5680
+ intervalSeconds,
5681
+ ...typeof expiresIn === "number" && Number.isFinite(expiresIn) ? { expiresIn } : {}
5682
+ };
5570
5683
  };
5571
5684
  var parseCliAuthPoll = (json2) => {
5572
5685
  if (typeof json2 !== "object" || json2 === null || !("status" in json2)) return null;
@@ -5625,13 +5738,32 @@ var browserCommand = (platform) => {
5625
5738
  return null;
5626
5739
  };
5627
5740
  var pollDelayMs = (intervalSeconds) => Math.min(Math.max(Math.round(intervalSeconds), 1), 10) * 1e3;
5628
- var pollDeadline = (expiresAt, now = Date.now()) => {
5629
- const at = Date.parse(expiresAt);
5630
- return Number.isNaN(at) ? now + 10 * 6e4 : at;
5741
+ var pollDeadline = (expiry, receivedAt, serverDate = null) => {
5742
+ if (expiry.expiresIn !== void 0) return receivedAt + Math.max(0, expiry.expiresIn) * 1e3;
5743
+ const at = Date.parse(expiry.expiresAt);
5744
+ const serverNow = serverDate === null ? Number.NaN : Date.parse(serverDate);
5745
+ if (Number.isNaN(at) || Number.isNaN(serverNow)) return receivedAt + 10 * 6e4;
5746
+ return receivedAt + Math.max(0, at - serverNow);
5747
+ };
5748
+ var isSet = (value) => value !== void 0 && value !== "";
5749
+ var browserDecision = (input) => {
5750
+ if (input.args.includes("--no-open")) return { open: false, why: null };
5751
+ if (input.args.includes("--open")) return { open: true, why: null };
5752
+ if (!input.isTTY) return { open: false, why: null };
5753
+ if (isSet(input.env["SSH_CONNECTION"]) || isSet(input.env["SSH_TTY"])) {
5754
+ return {
5755
+ open: false,
5756
+ why: "this terminal is over SSH, so no browser opens here: open the link on your own machine"
5757
+ };
5758
+ }
5759
+ if (input.platform === "linux" && !isSet(input.env["DISPLAY"]) && !isSet(input.env["WAYLAND_DISPLAY"])) {
5760
+ return { open: false, why: "no display here, so no browser opens: open the link elsewhere" };
5761
+ }
5762
+ return { open: browserCommand(input.platform) !== null, why: null };
5631
5763
  };
5632
5764
  var openBrowser = (url) => {
5633
5765
  const opener = browserCommand(process.platform);
5634
- if (opener === null || process.stdout.isTTY !== true) return;
5766
+ if (opener === null) return;
5635
5767
  try {
5636
5768
  const child = spawn2(opener.command, [...opener.args, url], {
5637
5769
  stdio: "ignore",
@@ -5653,18 +5785,19 @@ var post = async (url, body) => {
5653
5785
  } catch {
5654
5786
  return fail3(`cannot reach the Mend server at ${new URL(url).origin} \u2014 is it running?`);
5655
5787
  }
5788
+ const receivedAt = Date.now();
5656
5789
  const text = await response.text();
5657
5790
  let json2 = null;
5658
5791
  try {
5659
5792
  json2 = JSON.parse(text);
5660
5793
  } catch {
5661
5794
  }
5662
- return { status: response.status, json: json2 };
5795
+ return { status: response.status, json: json2, date: response.headers.get("date"), receivedAt };
5663
5796
  };
5664
5797
  var retryAfterSecondsOf = (json2) => {
5665
5798
  if (typeof json2 === "object" && json2 !== null && "retryAfterSeconds" in json2) {
5666
- const seconds2 = Number(json2.retryAfterSeconds);
5667
- if (Number.isFinite(seconds2) && seconds2 > 0) return seconds2;
5799
+ const seconds = Number(json2.retryAfterSeconds);
5800
+ if (Number.isFinite(seconds) && seconds > 0) return seconds;
5668
5801
  }
5669
5802
  return 5;
5670
5803
  };
@@ -5686,7 +5819,7 @@ var resolveServerUrl = async (args, deps) => {
5686
5819
  };
5687
5820
  var loginCommand = async (args, deps) => {
5688
5821
  const base = await resolveServerUrl(args, deps);
5689
- const started = await post(`${base}/api/cli/auth`, { name: os7.hostname() });
5822
+ const started = await post(`${base}/api/cli/auth`, { name: os6.hostname(), client: "cli" });
5690
5823
  if (started.status === 429) {
5691
5824
  return fail3(
5692
5825
  `the server asked for a pause \u2014 try again in ${retryAfterSecondsOf(started.json)}s`
@@ -5704,10 +5837,17 @@ var loginCommand = async (args, deps) => {
5704
5837
  ` ${dim3("code")} ${groupCode(opened.code)} ${dim3("\xB7 approve only if the browser shows the same code")}`
5705
5838
  );
5706
5839
  say3(` ${dim3("browser")} ${cobalt(url)}`);
5840
+ const browser = browserDecision({
5841
+ args,
5842
+ env: process.env,
5843
+ platform: process.platform,
5844
+ isTTY: process.stdout.isTTY === true
5845
+ });
5846
+ if (browser.why !== null) say3(` ${dim3(browser.why)}`);
5707
5847
  say3("");
5708
5848
  say3(dim3(" waiting for approval\u2026 Ctrl-C stops; nothing is granted until someone approves"));
5709
- openBrowser(url);
5710
- const deadline = pollDeadline(opened.expiresAt);
5849
+ if (browser.open) openBrowser(url);
5850
+ const deadline = pollDeadline(opened, started.receivedAt, started.date);
5711
5851
  const delay2 = pollDelayMs(opened.intervalSeconds);
5712
5852
  while (Date.now() < deadline) {
5713
5853
  await sleep2(delay2);
@@ -5860,10 +6000,10 @@ var SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set([".git", "node_modules"]);
5860
6000
  var scanFolder = (dir) => {
5861
6001
  const files = [];
5862
6002
  const skipped = [];
5863
- const walk3 = (relative5) => {
5864
- const entries = fs12.readdirSync(path12.join(dir, relative5), { withFileTypes: true }).toSorted((a, b) => a.name.localeCompare(b.name));
6003
+ const walk3 = (relative6) => {
6004
+ const entries = fs12.readdirSync(path12.join(dir, relative6), { withFileTypes: true }).toSorted((a, b) => a.name.localeCompare(b.name));
5865
6005
  for (const entry of entries) {
5866
- const child = relative5 === "" ? entry.name : `${relative5}/${entry.name}`;
6006
+ const child = relative6 === "" ? entry.name : `${relative6}/${entry.name}`;
5867
6007
  if (entry.isSymbolicLink()) {
5868
6008
  skipped.push({ path: child, reason: "symlink" });
5869
6009
  } else if (entry.isDirectory()) {
@@ -6141,9 +6281,9 @@ var operatorCommand = async (api2, tryApi, baseUrl, args) => {
6141
6281
 
6142
6282
  // src/pi-profile.ts
6143
6283
  import * as fs13 from "node:fs";
6144
- import * as os8 from "node:os";
6284
+ import * as os7 from "node:os";
6145
6285
  import * as path13 from "node:path";
6146
- var piAgentDir = () => process.env["PI_CODING_AGENT_DIR"] ?? path13.join(os8.homedir(), ".pi", "agent");
6286
+ var piAgentDir = () => process.env["PI_CODING_AGENT_DIR"] ?? path13.join(os7.homedir(), ".pi", "agent");
6147
6287
  var RESOURCE_DIRS = ["extensions", "themes", "prompts"];
6148
6288
  var BESIDE = [
6149
6289
  ["package.json", "package.json"],
@@ -6202,7 +6342,7 @@ var walk = (root, notes) => {
6202
6342
  return found;
6203
6343
  };
6204
6344
  var isLocalSource = (source) => !/^(npm|git):/.test(source) && !/^(https?|ssh|git):\/\//.test(source) && !source.startsWith("git@");
6205
- var expandHome = (source) => source === "~" || source.startsWith("~/") ? path13.join(os8.homedir(), source.slice(1)) : source;
6345
+ var expandHome = (source) => source === "~" || source.startsWith("~/") ? path13.join(os7.homedir(), source.slice(1)) : source;
6206
6346
  var bundleName = (abs) => {
6207
6347
  try {
6208
6348
  const manifest = JSON.parse(fs13.readFileSync(path13.join(abs, "package.json"), "utf8"));
@@ -6682,10 +6822,10 @@ var parseDuration = (text) => {
6682
6822
  };
6683
6823
  var DURATION_ISSUE = "--timeout takes a duration above 0: 90 or 90s, 5m, 1h";
6684
6824
  var durationLine = (ms) => {
6685
- const seconds2 = Math.round(ms / 1e3);
6686
- if (seconds2 < 60) return `${seconds2} s`;
6687
- const minutes = Math.floor(seconds2 / 60);
6688
- const rest = seconds2 % 60;
6825
+ const seconds = Math.round(ms / 1e3);
6826
+ if (seconds < 60) return `${seconds} s`;
6827
+ const minutes = Math.floor(seconds / 60);
6828
+ const rest = seconds % 60;
6689
6829
  if (minutes < 60) return rest === 0 ? `${minutes} min` : `${minutes} min ${rest} s`;
6690
6830
  const hours = Math.floor(minutes / 60);
6691
6831
  return minutes % 60 === 0 ? `${hours} h` : `${hours} h ${minutes % 60} min`;
@@ -6809,8 +6949,8 @@ var pickServiceAttempt = (services, needle, sessionId) => {
6809
6949
  import * as path14 from "node:path";
6810
6950
  var secretFilePathOf = (input, home) => {
6811
6951
  const trimmed = input.trim();
6812
- let relative5 = trimmed;
6813
- if (trimmed === "~" || trimmed.startsWith("~/")) relative5 = trimmed.slice(2);
6952
+ let relative6 = trimmed;
6953
+ if (trimmed === "~" || trimmed.startsWith("~/")) relative6 = trimmed.slice(2);
6814
6954
  else if (path14.isAbsolute(trimmed)) {
6815
6955
  const fromHome = path14.relative(home, trimmed);
6816
6956
  if (fromHome === "" || fromHome.startsWith("..") || path14.isAbsolute(fromHome)) {
@@ -6819,9 +6959,9 @@ var secretFilePathOf = (input, home) => {
6819
6959
  issue: `${trimmed} is outside your home directory; name the path under the workspace home, as .aws/credentials`
6820
6960
  };
6821
6961
  }
6822
- relative5 = fromHome;
6962
+ relative6 = fromHome;
6823
6963
  }
6824
- const normalized = path14.posix.normalize(relative5).replace(/^(\.\/)+/, "").replace(/\/$/, "");
6964
+ const normalized = path14.posix.normalize(relative6).replace(/^(\.\/)+/, "").replace(/\/$/, "");
6825
6965
  const issue = validateSecretFilePath(normalized === "." ? "" : normalized);
6826
6966
  return issue === null ? { path: normalized, issue: null } : { path: null, issue };
6827
6967
  };
@@ -6843,7 +6983,7 @@ import * as dns from "node:dns/promises";
6843
6983
  import * as fs16 from "node:fs";
6844
6984
  import { readFile } from "node:fs/promises";
6845
6985
  import * as net4 from "node:net";
6846
- import * as os10 from "node:os";
6986
+ import * as os9 from "node:os";
6847
6987
  import * as path16 from "node:path";
6848
6988
 
6849
6989
  // src/server-docker-volumes.ts
@@ -6852,7 +6992,7 @@ import { createHash as createHash2 } from "node:crypto";
6852
6992
  // src/server-store.ts
6853
6993
  import { randomUUID as randomUUID2 } from "node:crypto";
6854
6994
  import * as fs14 from "node:fs";
6855
- import * as os9 from "node:os";
6995
+ import * as os8 from "node:os";
6856
6996
  import * as path15 from "node:path";
6857
6997
  var ServerRefusal = class extends Error {
6858
6998
  };
@@ -6957,7 +7097,7 @@ var describeOwner = (lockDir) => {
6957
7097
  const owner = parseLockOwner(raw);
6958
7098
  if (owner === null) return "owner metadata is invalid";
6959
7099
  const label = `PID ${owner.pid} on ${owner.hostname}`;
6960
- if (owner.hostname !== os9.hostname()) return label;
7100
+ if (owner.hostname !== os8.hostname()) return label;
6961
7101
  try {
6962
7102
  process.kill(owner.pid, 0);
6963
7103
  return `${label} is still live`;
@@ -6971,6 +7111,27 @@ var describeOwner = (lockDir) => {
6971
7111
  var lockGuidance = (lockDir) => new ServerStoreError(
6972
7112
  `Server is busy: ${lockDir} is locked (${describeOwner(lockDir)}). Wait for the owning command. Never remove a live lock. For stale-lock recovery, verify on that host that the owner and its Docker Compose children have stopped, then move only this lock directory aside and retry. Keep identity.env, active, and generations intact.`
6973
7113
  );
7114
+ var heldLocks = /* @__PURE__ */ new Set();
7115
+ var afterRelease = [];
7116
+ var noteReleased = (lock) => {
7117
+ heldLocks.delete(lock);
7118
+ if (heldLocks.size > 0) return;
7119
+ const waiting = afterRelease;
7120
+ afterRelease = [];
7121
+ for (const callback of waiting) callback();
7122
+ };
7123
+ var whenServerLockReleased = (callback) => {
7124
+ if (heldLocks.size === 0) callback();
7125
+ else afterRelease.push(callback);
7126
+ };
7127
+ var releaseOnExit = false;
7128
+ var releaseHeldLocksOnExit = () => {
7129
+ if (releaseOnExit) return;
7130
+ releaseOnExit = true;
7131
+ process.on("exit", () => {
7132
+ for (const lock of heldLocks) lock.release();
7133
+ });
7134
+ };
6974
7135
  var acquireLock = (configDir, create) => {
6975
7136
  if (create) {
6976
7137
  fs14.mkdirSync(configDir, { recursive: true, mode: 448 });
@@ -6989,7 +7150,7 @@ var acquireLock = (configDir, create) => {
6989
7150
  }
6990
7151
  const owned = fs14.statSync(lockDir);
6991
7152
  const ownerFile = path15.join(lockDir, "owner.json");
6992
- const owner = `${JSON.stringify({ pid: process.pid, hostname: os9.hostname(), token: randomUUID2() })}
7153
+ const owner = `${JSON.stringify({ pid: process.pid, hostname: os8.hostname(), token: randomUUID2() })}
6993
7154
  `;
6994
7155
  let open = true;
6995
7156
  const assertOwned = () => {
@@ -7005,7 +7166,7 @@ var acquireLock = (configDir, create) => {
7005
7166
  } catch {
7006
7167
  throw lockGuidance(lockDir);
7007
7168
  }
7008
- return {
7169
+ const lock = {
7009
7170
  assertOwned,
7010
7171
  release: () => {
7011
7172
  const result = attempt(() => {
@@ -7014,9 +7175,13 @@ var acquireLock = (configDir, create) => {
7014
7175
  fs14.rmdirSync(lockDir);
7015
7176
  });
7016
7177
  open = false;
7178
+ noteReleased(lock);
7017
7179
  return result;
7018
7180
  }
7019
7181
  };
7182
+ heldLocks.add(lock);
7183
+ releaseHeldLocksOnExit();
7184
+ return lock;
7020
7185
  };
7021
7186
  var readIdentity = (paths) => {
7022
7187
  const identity = readOptional(paths.identity);
@@ -7092,8 +7257,8 @@ var prepareGeneration = (paths, files) => {
7092
7257
  return { directory, files };
7093
7258
  };
7094
7259
  var activateGeneration = (paths, generation) => {
7095
- const relative5 = path15.relative(paths.configDir, generation.directory);
7096
- if (!/^generations\/gen-[0-9a-f-]{36}$/.test(relative5) || readIdentity(paths) !== fs14.readFileSync(path15.join(generation.directory, "identity.env"), "utf8")) {
7260
+ const relative6 = path15.relative(paths.configDir, generation.directory);
7261
+ if (!/^generations\/gen-[0-9a-f-]{36}$/.test(relative6) || readIdentity(paths) !== fs14.readFileSync(path15.join(generation.directory, "identity.env"), "utf8")) {
7097
7262
  throw new ServerStoreError("Cannot activate a generation outside this installation identity.");
7098
7263
  }
7099
7264
  for (const [key, content] of allFiles(generation.files)) {
@@ -7102,7 +7267,7 @@ var activateGeneration = (paths, generation) => {
7102
7267
  }
7103
7268
  }
7104
7269
  const pointer = path15.join(paths.configDir, `.active-${randomUUID2()}`);
7105
- fs14.symlinkSync(relative5, pointer);
7270
+ fs14.symlinkSync(relative6, pointer);
7106
7271
  fs14.renameSync(pointer, paths.active);
7107
7272
  syncDirectory(paths.configDir);
7108
7273
  };
@@ -7822,7 +7987,13 @@ var flagsFor = (before, after) => {
7822
7987
  return flags;
7823
7988
  };
7824
7989
  var shellWord = (word) => /^[A-Za-z0-9_./:@=,+-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
7825
- var setupCommandOf = (flags) => ["mend", "server", "setup", ...flags.length === 0 ? ["--yes"] : flags.map(shellWord)].join(" ");
7990
+ var setupCommandOf = (flags, given = []) => [
7991
+ "mend",
7992
+ "server",
7993
+ "setup",
7994
+ ...flags.length === 0 ? ["--yes"] : flags.map(shellWord),
7995
+ ...given.map(shellWord)
7996
+ ].join(" ");
7826
7997
  var sshAt = (settings) => settings.sshBind ?? settings.bind;
7827
7998
  var sshBeyondThisMachine = (settings) => !isLoopbackAddress(sshAt(settings));
7828
7999
  var reachOf = (settings) => settings.edgeHost !== void 0 ? `the public internet, over HTTPS at ${settings.edgeHost} (the edge, Caddy, on 80 and 443)` : isLoopbackAddress(settings.bind) ? `this machine only, at ${settings.appUrl}` : `your network, at ${settings.appUrl} (listening on ${settings.bind})`;
@@ -8190,7 +8361,8 @@ var askSsh = async (asked, settings, publishedBefore = sshAt(settings)) => {
8190
8361
  value: at
8191
8362
  }
8192
8363
  ];
8193
- const current = isLoopbackAddress(at) ? 0 : choices.findIndex((choice) => choice.value === at);
8364
+ const stated = settings.declared.includes("workspace-ssh");
8365
+ const current = isLoopbackAddress(at) || settings.exposure === "public" && !stated ? 0 : choices.findIndex((choice) => choice.value === at);
8194
8366
  const chosen = await choose(
8195
8367
  io,
8196
8368
  `Should VS Code Remote-SSH and mend ssh reach sessions from other machines?${settings.edgeHost === void 0 ? " Workspace SSH" : " The edge carries HTTPS only; workspace SSH"} is a port of its own.`,
@@ -8204,7 +8376,7 @@ var askSsh = async (asked, settings, publishedBefore = sshAt(settings)) => {
8204
8376
  });
8205
8377
  if (isLoopbackAddress(chosen)) return onLoopback();
8206
8378
  if (settings.exposure !== "public") return settled({ ...settings, sshBind: chosen });
8207
- const declared = settings.declared.includes("workspace-ssh") && at === chosen;
8379
+ const declared = stated && at === chosen;
8208
8380
  const checked = await choose(
8209
8381
  io,
8210
8382
  `Mend cannot see who reaches ${publishedAddress(chosen, port)} from outside, and a public server does not start until you state that you checked (the exposure gate's workspace-ssh item).`,
@@ -8438,8 +8610,14 @@ var askOrigins = async (asked, settings) => {
8438
8610
  var walk2 = async (asked, settings) => {
8439
8611
  let next = await askReach(asked, settings);
8440
8612
  next = await askT3(asked, next);
8441
- if (next.exposure === "public" && await yesNo(asked.io, "State what you have checked from outside the network now?", false))
8442
- next = await askDeclarations(asked, next);
8613
+ if (next.exposure === "public") {
8614
+ asked.io.write("");
8615
+ asked.io.write(
8616
+ "The public exposure gate has items Mend cannot observe from inside; each stays open until you state you checked it from outside. You can state them now, or later with mend server setup --declare."
8617
+ );
8618
+ if (await yesNo(asked.io, "State what you have checked from outside the network now?", false))
8619
+ next = await askDeclarations(asked, next);
8620
+ }
8443
8621
  next = await askMirrors(asked, next, true);
8444
8622
  return askTenancy(asked, next);
8445
8623
  };
@@ -8483,6 +8661,61 @@ var changeOne = async (asked, settings) => {
8483
8661
  if (!await yesNo(asked.io, "Change something else?", false)) return next;
8484
8662
  }
8485
8663
  };
8664
+ var portOf = (input) => {
8665
+ if (!/^\d+$/.test(input)) return null;
8666
+ const port = Number(input);
8667
+ return port >= 1 && port <= 65535 ? port : null;
8668
+ };
8669
+ var withAppPort = (settings, port) => {
8670
+ const url = new URL(settings.appUrl);
8671
+ if (settings.edgeHost === void 0 && url.port === String(settings.appPort))
8672
+ url.port = String(port);
8673
+ return { ...settings, appPort: port, appUrl: url.origin };
8674
+ };
8675
+ var settlePorts = async (asked, settings) => {
8676
+ const { io, context } = asked;
8677
+ const ours = (port) => context.saved !== null && (context.saved.appPort === port || context.saved.sshPort === port);
8678
+ let next = settings;
8679
+ for (const what of ["web", "ssh"]) {
8680
+ const port = what === "web" ? next.appPort : next.sshPort;
8681
+ const other = what === "web" ? next.sshPort : next.appPort;
8682
+ const address = what === "web" ? next.bind : next.sshBind ?? next.bind;
8683
+ if (ours(port)) continue;
8684
+ const holder = await context.observe.portHolder(address, port, what);
8685
+ if (holder === null) continue;
8686
+ io.write("");
8687
+ io.write(`Observed: ${publishedAddress(address, port)} is taken: ${holder}.`);
8688
+ const usable = async (candidate) => candidate !== other && candidate !== next.t3GatewayPort && (ours(candidate) || !await context.observe.portTaken(candidate, address));
8689
+ let free;
8690
+ for (let candidate = port + 1; candidate <= Math.min(port + 100, 65535); candidate += 1)
8691
+ if (await usable(candidate)) {
8692
+ free = candidate;
8693
+ break;
8694
+ }
8695
+ let picked;
8696
+ while (picked === void 0) {
8697
+ const answered = await typed(
8698
+ io,
8699
+ what === "web" ? "Mend's web port" : "The workspace SSH port",
8700
+ free === void 0 ? void 0 : String(free),
8701
+ (input) => {
8702
+ const parsed = portOf(input);
8703
+ if (parsed === null) return { refused: "A port is a whole number from 1 to 65535." };
8704
+ if (parsed === other)
8705
+ return { refused: `${parsed} is the ${what === "web" ? "SSH" : "web"} port.` };
8706
+ if (parsed === next.t3GatewayPort)
8707
+ return { refused: `${parsed} is the T3 Code gateway's port.` };
8708
+ return { value: parsed };
8709
+ }
8710
+ );
8711
+ const taken = ours(answered) ? null : await context.observe.portHolder(address, answered, what);
8712
+ if (taken === null) picked = answered;
8713
+ else io.write(` ${publishedAddress(address, answered)} is taken too: ${taken}.`);
8714
+ }
8715
+ next = what === "web" ? withAppPort(next, picked) : { ...next, sshPort: picked };
8716
+ }
8717
+ return next;
8718
+ };
8486
8719
  var runGuide = async (io, context) => {
8487
8720
  const base = context.saved ?? context.defaults;
8488
8721
  const asked = {
@@ -8516,7 +8749,7 @@ var runGuide = async (io, context) => {
8516
8749
  );
8517
8750
  target = how === "keep" ? base : how === "change" ? await changeOne(asked, base) : await walk2(asked, base);
8518
8751
  }
8519
- target = settled(target);
8752
+ target = await settlePorts(asked, settled(target));
8520
8753
  const flags = flagsFor(base, target);
8521
8754
  let resolved;
8522
8755
  try {
@@ -8542,7 +8775,7 @@ var runGuide = async (io, context) => {
8542
8775
  for (const line of changes) io.write(line);
8543
8776
  }
8544
8777
  }
8545
- io.write(`Same as: ${setupCommandOf(flags)}`);
8778
+ io.write(`Same as: ${setupCommandOf(flags, context.given)}`);
8546
8779
  const unresolvedEdge = target.edgeHost !== void 0 && asked.unresolved.has(target.edgeHost) ? target.edgeHost : null;
8547
8780
  if (unresolvedEdge !== null)
8548
8781
  io.write(
@@ -8766,14 +8999,14 @@ var parseSetupOptions = (args) => {
8766
8999
  previous.push(value);
8767
9000
  values.set(flag, previous);
8768
9001
  }
8769
- const flagValue3 = (flag) => values.get(flag)?.[0];
8770
- const version = flagValue3("--version");
8771
- const appPort = flagValue3("--port");
8772
- const sshPort = flagValue3("--ssh-port");
9002
+ const flagValue2 = (flag) => values.get(flag)?.[0];
9003
+ const version = flagValue2("--version");
9004
+ const appPort = flagValue2("--port");
9005
+ const sshPort = flagValue2("--ssh-port");
8773
9006
  const origins = values.get("--origin");
8774
- const edge = flagValue3("--edge");
8775
- const exposure = flagValue3("--exposure");
8776
- const tenancy = flagValue3("--tenancy");
9007
+ const edge = flagValue2("--edge");
9008
+ const exposure = flagValue2("--exposure");
9009
+ const tenancy = flagValue2("--tenancy");
8777
9010
  const declared = values.get("--declare");
8778
9011
  const declaredItems = declared === void 0 ? void 0 : parseDeclared(declared, "--declare");
8779
9012
  const undeclared = parseDeclared(values.get("--undeclare") ?? [], "--undeclare");
@@ -8792,7 +9025,7 @@ var parseSetupOptions = (args) => {
8792
9025
  };
8793
9026
  const npmMirror = pair("--npm-mirror", "--no-npm-mirror");
8794
9027
  const dockerMirror = pair("--docker-mirror", "--no-docker-mirror");
8795
- const maxSize = flagValue3("--npm-mirror-max-size");
9028
+ const maxSize = flagValue2("--npm-mirror-max-size");
8796
9029
  const npmMirrorMaxSize = maxSize === void 0 ? void 0 : parseMirrorSize(maxSize);
8797
9030
  if (npmMirrorMaxSize === null)
8798
9031
  throw setupError(
@@ -8800,7 +9033,7 @@ var parseSetupOptions = (args) => {
8800
9033
  );
8801
9034
  if (npmMirrorMaxSize !== void 0 && npmMirror === false)
8802
9035
  throw setupError("--npm-mirror-max-size and --no-npm-mirror contradict each other.");
8803
- const dockerMaxSize = flagValue3("--docker-mirror-max-size");
9036
+ const dockerMaxSize = flagValue2("--docker-mirror-max-size");
8804
9037
  const dockerMirrorMaxSize = dockerMaxSize === void 0 ? void 0 : parseMirrorSize(dockerMaxSize);
8805
9038
  if (dockerMirrorMaxSize === null)
8806
9039
  throw setupError(
@@ -8808,7 +9041,7 @@ var parseSetupOptions = (args) => {
8808
9041
  );
8809
9042
  if (dockerMirrorMaxSize !== void 0 && dockerMirror === false)
8810
9043
  throw setupError("--docker-mirror-max-size and --no-docker-mirror contradict each other.");
8811
- const dockerHubUsername = flagValue3("--docker-hub-username");
9044
+ const dockerHubUsername = flagValue2("--docker-hub-username");
8812
9045
  const dockerHubTokenStdin = values.has("--docker-hub-token-stdin");
8813
9046
  const noDockerHubLogin = values.has("--no-docker-hub-login");
8814
9047
  if (dockerHubUsername === void 0 !== !dockerHubTokenStdin)
@@ -8830,22 +9063,22 @@ var parseSetupOptions = (args) => {
8830
9063
  throw setupError(
8831
9064
  `--docker-hub-username and ${noDockerHubLogin ? "--no-docker-hub-login" : "--no-docker-mirror"} contradict each other.`
8832
9065
  );
8833
- const t3GatewayPort = flagValue3("--t3-gateway-port");
9066
+ const t3GatewayPort = flagValue2("--t3-gateway-port");
8834
9067
  if (values.has("--no-t3-gateway") && (values.has("--t3-gateway") || t3GatewayPort !== void 0)) {
8835
9068
  throw setupError("--no-t3-gateway contradicts --t3-gateway and --t3-gateway-port.");
8836
9069
  }
8837
9070
  return {
8838
- context: flagValue3("--context"),
9071
+ context: flagValue2("--context"),
8839
9072
  version: version === void 0 ? void 0 : parseVersion(version),
8840
- bind: flagValue3("--bind"),
8841
- sshBind: flagValue3("--ssh-bind"),
8842
- url: flagValue3("--url"),
9073
+ bind: flagValue2("--bind"),
9074
+ sshBind: flagValue2("--ssh-bind"),
9075
+ url: flagValue2("--url"),
8843
9076
  // `--origin none`: no extra origins at all.
8844
9077
  origins: origins === void 0 ? void 0 : origins[0] === "none" ? [] : origins,
8845
9078
  appPort: appPort === void 0 ? void 0 : parsePort(appPort, "--port"),
8846
9079
  sshPort: sshPort === void 0 ? void 0 : parsePort(sshPort, "--ssh-port"),
8847
- dockerSocket: flagValue3("--docker-socket"),
8848
- assetsDir: flagValue3("--assets-dir"),
9080
+ dockerSocket: flagValue2("--docker-socket"),
9081
+ assetsDir: flagValue2("--assets-dir"),
8849
9082
  offline: values.has("--offline"),
8850
9083
  edge: edge === void 0 ? void 0 : parseEdge(edge),
8851
9084
  noEdge: values.has("--no-edge"),
@@ -8868,6 +9101,16 @@ var parseSetupOptions = (args) => {
8868
9101
  };
8869
9102
  };
8870
9103
  var HOST_FLAGS = /* @__PURE__ */ new Set(["--allow-userns", "--no-allow-userns"]);
9104
+ var ENGINE_FLAGS = /* @__PURE__ */ new Set(["--context", "--docker-socket"]);
9105
+ var answersNoQuestion = (args) => {
9106
+ for (let index = 0; index < args.length; index += 1) {
9107
+ const arg = args[index] ?? "";
9108
+ if (HOST_FLAGS.has(arg)) continue;
9109
+ if (!ENGINE_FLAGS.has(arg)) return false;
9110
+ index += 1;
9111
+ }
9112
+ return true;
9113
+ };
8871
9114
  var resolveMirrors = (saved, options) => {
8872
9115
  const base = saved ?? DEFAULT_MIRRORS;
8873
9116
  const npmOn = options.npmMirror ?? (options.npmMirrorMaxSize !== void 0 || base.npm !== null);
@@ -9387,7 +9630,8 @@ var checkDocker = async (runtime, context) => {
9387
9630
  }
9388
9631
  return info.stdout.trim();
9389
9632
  };
9390
- var HOST_HELPER_IMAGE = "postgres:17-alpine";
9633
+ var NETWORK_GUARD_IMAGE = "busybox:1.37@sha256:bdf57e528e45e4433820e045b29b4597825a1c9e38353532d90a01445013f82e";
9634
+ var HOST_HELPER_IMAGE = NETWORK_GUARD_IMAGE;
9391
9635
  var observeHostUserNamespaces = async (runtime, context) => {
9392
9636
  const read = HOST_USER_NAMESPACE_FILES.map(
9393
9637
  (file) => `printf '%s|' "$(cat ${file} 2>/dev/null || echo -)"`
@@ -9413,7 +9657,8 @@ var observeHostUserNamespaces = async (runtime, context) => {
9413
9657
  unprivilegedUsernsClone: clone ?? null
9414
9658
  });
9415
9659
  };
9416
- var userNamespacesReminder = (setting) => `No session can start on this Docker host yet: its kernel refuses unprivileged user namespaces, which each workspace's rootless Docker service needs. On the host, run: ${hostUserNamespacesFix(setting)}`;
9660
+ var ALLOW_USERNS_RERUN = "Re-run mend server setup with --allow-userns to let setup write it (and let mend uninstall undo it). Or, on the host, run:";
9661
+ var userNamespacesReminder = (setting, how = "On the host, run:") => `No session can start on this Docker host yet: its kernel refuses unprivileged user namespaces, which each workspace's rootless Docker service needs. ${how} ${hostUserNamespacesFix(setting)}`;
9417
9662
  var sysctlOf = (setting) => {
9418
9663
  const match = /^([a-z0-9_.]+) = ([0-9]+)$/.exec(setting);
9419
9664
  if (match?.[1] === void 0 || match[2] === void 0) return null;
@@ -9474,10 +9719,10 @@ var settleHostUserNamespaces = async (runtime, options, context) => {
9474
9719
  runtime.writeLine(
9475
9720
  `Sessions cannot start on this host yet: ${who} blocks the unprivileged user namespaces each workspace's Docker service needs.`
9476
9721
  );
9477
- const printFix = (why) => {
9478
- runtime.writeLine(`${why} On the host, run: ${fix}`);
9722
+ const printFix = (why, how = "On the host, run:") => {
9723
+ runtime.writeLine(`${why} ${how} ${fix}`);
9479
9724
  runtime.writeLine("");
9480
- return userNamespacesReminder(observed.setting);
9725
+ return userNamespacesReminder(observed.setting, how);
9481
9726
  };
9482
9727
  if (await rootlessDaemon(runtime, context)) {
9483
9728
  return printFix(
@@ -9490,13 +9735,12 @@ var settleHostUserNamespaces = async (runtime, options, context) => {
9490
9735
  `Allowing them writes ${observed.setting} to ${HOST_USER_NAMESPACE_SYSCTL_FILE} on the Docker host and applies it now. It lifts that restriction for the whole host, not only for Mend.`
9491
9736
  );
9492
9737
  const answer2 = await runtime.prompter("Allow them now? [Y/n] ");
9493
- if (answer2 === null) throw setupError("Stopped before anything was pulled; nothing changed.");
9738
+ if (answer2 === null) throw setupError("Stopped before setup changed anything.");
9494
9739
  allow = !/^n/i.test(answer2.trim());
9495
9740
  }
9741
+ if (allow === false) return printFix("Left as it is (--no-allow-userns or your answer).");
9496
9742
  if (allow !== true) {
9497
- return printFix(
9498
- allow === false ? "Left as it is (--no-allow-userns or your answer)." : "Setup changes the host's kernel only when asked: answer the question on a terminal, or pass --allow-userns."
9499
- );
9743
+ return printFix("Setup changes the host's kernel only when asked.", ALLOW_USERNS_RERUN);
9500
9744
  }
9501
9745
  const stopped = await allowHostUserNamespaces(runtime, context, observed.setting);
9502
9746
  if (stopped !== null) return printFix(`Setup could not apply it through Docker (${stopped}).`);
@@ -9809,6 +10053,25 @@ var envKeyNames = (env) => env.split("\n").flatMap((line) => {
9809
10053
  const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=/.exec(line);
9810
10054
  return match?.[1] === void 0 ? [] : [match[1]];
9811
10055
  });
10056
+ var readLocalServer = async (configDir) => {
10057
+ const result = await withServerStore(
10058
+ configDir,
10059
+ async (store) => {
10060
+ const installation = storeValue(readServerInstallation(store));
10061
+ const identity = storeValue(store.readIdentity());
10062
+ if (installation === null || identity === null) return null;
10063
+ return {
10064
+ url: installation.config.appUrl,
10065
+ dockerContext: installation.config.dockerContext,
10066
+ version: installation.config.serverVersion,
10067
+ instance: instanceIdOf(parseSecrets(identity).betterAuthSecret)
10068
+ };
10069
+ },
10070
+ { create: false }
10071
+ );
10072
+ if (result._tag === "error") throw result.error;
10073
+ return result.value;
10074
+ };
9812
10075
  var readServerInstallationFacts = async (configDir) => {
9813
10076
  const result = await withServerStore(
9814
10077
  configDir,
@@ -9875,25 +10138,86 @@ var observeT3Gateway = async (runtime, port) => {
9875
10138
  }
9876
10139
  return `The t3code gateway did not answer at 127.0.0.1:${port} from this machine within about a minute. Mend runs without it; mend server logs shows what it said, and mend server status looks again.`;
9877
10140
  };
9878
- var probeHealth = async (runtime, appUrl, expectedVersion) => {
9879
- const healthUrl = `${appUrl}/api/health`;
10141
+ var instanceIdOf = (betterAuthSecret) => createHmac("sha256", betterAuthSecret).update("mend instance id").digest("hex").slice(0, 32);
10142
+ var readHealth = (response) => {
10143
+ if (response.error !== void 0) return { kind: "other", failure: response.error };
10144
+ if (response.status < 200 || response.status >= 300)
10145
+ return { kind: "other", failure: `HTTP ${response.status}` };
10146
+ let fields;
10147
+ try {
10148
+ fields = ownFields(JSON.parse(response.body));
10149
+ } catch {
10150
+ return { kind: "other", failure: "health response is not valid JSON" };
10151
+ }
10152
+ const version = fields?.get("version");
10153
+ const instance = fields?.get("instance");
10154
+ if (fields === null || typeof version !== "string")
10155
+ return { kind: "other", failure: "health response names no Mend version" };
10156
+ return {
10157
+ kind: "mend",
10158
+ ok: fields.get("status") === "ok",
10159
+ version,
10160
+ instance: typeof instance === "string" ? instance : void 0
10161
+ };
10162
+ };
10163
+ var isThisInstall = (answer2, version, instance) => answer2.kind === "mend" && answer2.ok && answer2.version === version && (answer2.instance === void 0 || answer2.instance === instance);
10164
+ var connectHost = (address) => address === "0.0.0.0" ? "127.0.0.1" : address === "::" ? "::1" : address;
10165
+ var portHolder = async (runtime, address, port, what) => {
10166
+ if (runtime.portTaken === void 0 || !await runtime.portTaken(port, address)) return null;
10167
+ if (what === "ssh") return "something else listens there";
10168
+ const host = connectHost(address);
10169
+ const answer2 = readHealth(
10170
+ await runtime.fetchText(
10171
+ `http://${net4.isIPv6(host) ? `[${host}]` : host}:${port}/api/health`,
10172
+ 2e3
10173
+ )
10174
+ );
10175
+ return answer2.kind === "mend" ? `another Mend, ${answer2.version}, answers there` : "something else listens there";
10176
+ };
10177
+ var refuseTakenPorts = async (runtime, wanted, existing) => {
10178
+ const ours = (port) => existing !== null && (existing.appPort === port || existing.sshPort === port);
10179
+ const taken = [];
10180
+ const flags = [];
10181
+ for (const [what, address, port, flag, name] of [
10182
+ ["web", wanted.bind, wanted.appPort, "--port <n>", "Mend's web port"],
10183
+ ["ssh", wanted.sshBind ?? wanted.bind, wanted.sshPort, "--ssh-port <n>", "workspace SSH"]
10184
+ ]) {
10185
+ if (ours(port)) continue;
10186
+ const holder = await portHolder(runtime, address, port, what);
10187
+ if (holder === null) continue;
10188
+ taken.push(`${publishedAddress(address, port)}, ${name}, is taken: ${holder}.`);
10189
+ flags.push(flag);
10190
+ }
10191
+ if (taken.length === 0) return;
10192
+ throw setupError(
10193
+ `${taken.join(" ")} Setup changed nothing. Choose ${flags.length === 1 ? "another port" : "other ports"} with ${flags.join(" ")}, or stop what holds ${flags.length === 1 ? "it" : "them"}, then run mend server setup again.`
10194
+ );
10195
+ };
10196
+ var probeHealth = async (runtime, config, instance) => {
10197
+ const healthUrl = `${healthOrigin(config)}/api/health`;
10198
+ const expectedVersion = config.serverVersion;
9880
10199
  let lastFailure = "request did not complete";
10200
+ let other;
9881
10201
  for (let attempt2 = 0; attempt2 < 30; attempt2 += 1) {
9882
- const response = await runtime.fetchText(healthUrl, 2e3);
9883
- lastFailure = response.error ?? `HTTP ${response.status}`;
9884
- if (response.error === void 0 && response.status >= 200 && response.status < 300) {
9885
- try {
9886
- const decoded = JSON.parse(response.body);
9887
- const fields = ownFields(decoded);
9888
- if (fields?.get("status") === "ok" && fields.get("version") === expectedVersion) return;
9889
- lastFailure = `health response must report status ok and version ${expectedVersion}`;
9890
- } catch {
9891
- lastFailure = "health response is not valid JSON";
9892
- }
9893
- }
10202
+ const answer2 = readHealth(await runtime.fetchText(healthUrl, 2e3));
10203
+ if (isThisInstall(answer2, expectedVersion, instance)) return;
10204
+ other = void 0;
10205
+ if (answer2.kind === "other") lastFailure = answer2.failure;
10206
+ else if (answer2.ok && answer2.instance !== void 0 && answer2.instance !== instance) {
10207
+ other = answer2;
10208
+ lastFailure = `another Mend install, ${answer2.version}, answers there`;
10209
+ } else if (answer2.ok && answer2.version !== expectedVersion) {
10210
+ other = answer2;
10211
+ lastFailure = `Mend ${answer2.version} answers there, not ${expectedVersion}`;
10212
+ } else lastFailure = `health response must report status ok and version ${expectedVersion}`;
9894
10213
  if (attempt2 % 10 === 0) runtime.writeLine(`Waiting for ${healthUrl} (${lastFailure})`);
9895
10214
  if (attempt2 < 29) await runtime.sleep(2e3);
9896
10215
  }
10216
+ if (other !== void 0) {
10217
+ throw setupError(
10218
+ `Mend started, but ${healthUrl} is not the Mend setup just started: ${lastFailure}. When another server holds port ${config.appPort} on this machine (another Docker engine, an older install), Docker cannot publish this one there. Choose another port with --port <n>, or stop what holds it, then run mend server setup again.`
10219
+ );
10220
+ }
9897
10221
  throw setupError(
9898
10222
  `Mend started, but ${healthUrl} did not answer successfully (${lastFailure}). Check the Mend container logs in Docker, then retry mend server setup.`
9899
10223
  );
@@ -10296,7 +10620,15 @@ var mirrorsChangedLines = (before, config) => {
10296
10620
  );
10297
10621
  return lines;
10298
10622
  };
10299
- var UNASKED_FRESH_SETUP = "No terminal to ask on and no flags, so setup does not guess how this Mend is reached. Run mend server setup in a terminal to answer its questions, or say it with flags: --yes takes the defaults (this machine only, http://localhost:3105); --bind <address> --url <origin> serves a private network (a tailnet, a LAN, a VPN); for public HTTPS, set up on this machine first, create the first account, then run mend server setup --edge <host> --exposure public. mend help server setup lists every flag.";
10623
+ var UNASKED_FRESH_SETUP = "No terminal to ask on, and no flag says how this Mend is reached (--context and --docker-socket only choose the Docker engine), so setup does not guess. Run mend server setup in a terminal to answer its questions, or say it with flags: --yes takes the defaults (this machine only, http://localhost:3105); --bind <address> --url <origin> serves a private network (a tailnet, a LAN, a VPN); for public HTTPS, set up on this machine first, create the first account, then run mend server setup --edge <host> --exposure public. mend help server setup lists every flag.";
10624
+ var requestedDockerContext = (runtime, options, existing) => {
10625
+ const variable = runtime.dockerContextVariable;
10626
+ const fromVariable = options.context === void 0 && existing === null && variable !== void 0;
10627
+ return {
10628
+ requested: options.context ?? (fromVariable ? variable : existing?.config.dockerContext),
10629
+ fromVariable
10630
+ };
10631
+ };
10300
10632
  var refuseLegacyContract = (existing) => {
10301
10633
  if (existing !== null && existing.config.assetContract !== ASSET_CONTRACT) {
10302
10634
  throw setupError(
@@ -10315,7 +10647,8 @@ var guideObservations = (runtime) => ({
10315
10647
  },
10316
10648
  lookupHost: runtime.lookupHost ?? (async () => null),
10317
10649
  localAddresses: runtime.localAddresses ?? (() => []),
10318
- portTaken: runtime.portTaken ?? (async () => false)
10650
+ portTaken: runtime.portTaken ?? (async () => false),
10651
+ portHolder: (address, port, what) => portHolder(runtime, address, port, what)
10319
10652
  });
10320
10653
  var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10321
10654
  if (runtime.platform !== "linux" && runtime.platform !== "darwin") {
@@ -10329,13 +10662,25 @@ var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10329
10662
  if (read._tag === "error") return { _tag: "error", message: read.error.message };
10330
10663
  const existing = read.value;
10331
10664
  refuseLegacyContract(existing);
10665
+ const hostOptions = parseSetupOptions(hostFlags2);
10666
+ const context = await selectDockerContext(
10667
+ runtime,
10668
+ requestedDockerContext(runtime, hostOptions, existing).requested
10669
+ );
10670
+ await checkDocker(runtime, context.name);
10671
+ const reminder = await settleHostUserNamespaces(
10672
+ { ...runtime, prompter },
10673
+ hostOptions,
10674
+ context.name
10675
+ );
10332
10676
  const outcome = await runGuide(
10333
10677
  { write: runtime.writeLine, ask: prompter },
10334
10678
  {
10335
10679
  saved: existing === null ? null : resolveSetupSettings(existing.config, []),
10336
10680
  defaults: resolveSetupSettings(null, []),
10337
10681
  observe: guideObservations(runtime),
10338
- resolve: (flags) => resolveSetupSettings(existing?.config ?? null, flags)
10682
+ resolve: (flags) => resolveSetupSettings(existing?.config ?? null, flags),
10683
+ given: hostFlags2
10339
10684
  }
10340
10685
  );
10341
10686
  if (outcome._tag === "refused") return { _tag: "error", message: outcome.message };
@@ -10346,7 +10691,8 @@ var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10346
10691
  return underLock(
10347
10692
  runtime.configDir,
10348
10693
  (store) => setupServer([...outcome.flags, ...hostFlags2], runtime, store, {
10349
- askedAgainst: existing?.directory ?? null
10694
+ askedAgainst: existing?.directory ?? null,
10695
+ userNamespaces: { reminder }
10350
10696
  }),
10351
10697
  { create: true }
10352
10698
  );
@@ -10379,7 +10725,7 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10379
10725
  "The install changed while you answered: another mend server setup or upgrade ran. This one changed nothing; run mend server setup again to see the install as it is now."
10380
10726
  );
10381
10727
  }
10382
- if (run2.askedAgainst === void 0 && args.every((arg) => HOST_FLAGS.has(arg)) && existing === null) {
10728
+ if (run2.askedAgainst === void 0 && answersNoQuestion(args) && existing === null) {
10383
10729
  throw setupError(UNASKED_FRESH_SETUP);
10384
10730
  }
10385
10731
  const savedIdentity = storeValue(store.readIdentity());
@@ -10390,13 +10736,24 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10390
10736
  );
10391
10737
  }
10392
10738
  refuseLegacyContract(existing);
10393
- const selectedContext = await selectDockerContext(
10739
+ const variable = runtime.dockerContextVariable;
10740
+ const { requested, fromVariable } = requestedDockerContext(runtime, options, existing);
10741
+ const selectedContext = await selectDockerContext(runtime, requested);
10742
+ const operatingSystem = await checkDocker(runtime, selectedContext.name);
10743
+ runtime.writeLine(
10744
+ `Using Docker context "${selectedContext.name}" (${selectedContext.endpoint})${fromVariable ? ", from DOCKER_CONTEXT" : ""}`
10745
+ );
10746
+ if (existing !== null && options.context === void 0 && variable !== void 0 && variable !== existing.config.dockerContext) {
10747
+ runtime.writeLine(
10748
+ `DOCKER_CONTEXT is "${variable}"; this install runs on Docker context "${existing.config.dockerContext}", where its data is, and stays there. --context moves it.`
10749
+ );
10750
+ }
10751
+ await refuseTakenPorts(
10394
10752
  runtime,
10395
- options.context ?? existing?.config.dockerContext
10753
+ validateExposure(existing?.config ?? null, options),
10754
+ existing?.config ?? null
10396
10755
  );
10397
- const operatingSystem = await checkDocker(runtime, selectedContext.name);
10398
- runtime.writeLine(`Using Docker context "${selectedContext.name}" (${selectedContext.endpoint})`);
10399
- const userNamespaces = await settleHostUserNamespaces(runtime, options, selectedContext.name);
10756
+ const userNamespaces = run2.userNamespaces === void 0 ? await settleHostUserNamespaces(runtime, options, selectedContext.name) : run2.userNamespaces.reminder;
10400
10757
  const serverVersion = await resolveServerVersion(runtime, options, existing?.config ?? null);
10401
10758
  const mirrors = resolveMirrors(existing?.config.mirrors, options);
10402
10759
  const configWithoutBucket = {
@@ -10424,8 +10781,11 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10424
10781
  "--format",
10425
10782
  "{{json .}}"
10426
10783
  ]);
10427
- const line = dockerShutdownSetupLine(
10428
- readShutdownTimeout(runtime.dockerDaemonFacts(info.status === 0 ? info.stdout : null))
10784
+ const line = dockerStopSetupLine(
10785
+ readDockerStop(
10786
+ runtime.dockerDaemonFacts(info.status === 0 ? info.stdout : null, selectedContext.name),
10787
+ WORKSPACE_STOP_TIMEOUT_SECONDS
10788
+ )
10429
10789
  );
10430
10790
  if (line !== null) runtime.writeLine(line);
10431
10791
  }
@@ -10482,7 +10842,8 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10482
10842
  storeValue(store.activate(generation));
10483
10843
  await startCompose(runtime, installation);
10484
10844
  await initGarage(runtime, installation, secrets);
10485
- await probeHealth(runtime, healthOrigin(config), config.serverVersion);
10845
+ const instance = instanceIdOf(secrets.betterAuthSecret);
10846
+ await probeHealth(runtime, config, instance);
10486
10847
  runtime.writeLine(reachableLine(config));
10487
10848
  const edgeStarted = edgeStartedLine(config);
10488
10849
  if (edgeStarted !== null) runtime.writeLine(edgeStarted);
@@ -10503,14 +10864,14 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10503
10864
  }
10504
10865
  for (const line of mirrorsChangedLines(existing?.config.mirrors, config)) runtime.writeLine(line);
10505
10866
  const urlChanged = existing !== null && existing.config.appUrl !== config.appUrl;
10506
- const cliHere = urlChanged ? await followUrlChange(runtime, options, existing.config, config) : runtime.savedCliLogin?.(runtime.configDir) ?? null;
10867
+ const cliHere = urlChanged ? await followUrlChange(runtime, options, existing.config, config, instance) : await offerCliHere(runtime, options, existing?.config ?? null, config, instance);
10507
10868
  const users = await instanceUsers(runtime, healthOrigin(config));
10508
10869
  if (users === "none" || users === null && existing === null) {
10509
10870
  runtime.writeLine(
10510
10871
  `Open ${config.appUrl}, create the first account, then run: mend login --url ${config.appUrl}`
10511
10872
  );
10512
10873
  } else if (urlChanged) {
10513
- } else if (cliHere === null || !cliHere.signedIn || !await answersAs(runtime, cliHere.url, config.serverVersion)) {
10874
+ } else if (cliHere === null || !cliHere.signedIn || !await answersAs(runtime, cliHere.url, config.serverVersion, instance)) {
10514
10875
  runtime.writeLine(
10515
10876
  `Open ${config.appUrl} to sign in. To sign in this machine's CLI, run: mend login --url ${config.appUrl}`
10516
10877
  );
@@ -10527,15 +10888,35 @@ var instanceUsers = async (runtime, origin) => {
10527
10888
  return null;
10528
10889
  }
10529
10890
  };
10530
- var answersAs = async (runtime, url, version) => {
10531
- const response = await runtime.fetchText(`${url.replace(/\/+$/, "")}/api/health`, 3e3);
10532
- if (response.error !== void 0 || response.status !== 200) return false;
10533
- try {
10534
- const fields = ownFields(JSON.parse(response.body));
10535
- return fields?.get("status") === "ok" && fields.get("version") === version;
10536
- } catch {
10537
- return false;
10891
+ var answersAs = async (runtime, url, version, instance) => isThisInstall(await healthAt(runtime, url), version, instance);
10892
+ var healthAt = async (runtime, url) => readHealth(await runtime.fetchText(`${url.replace(/\/+$/, "")}/api/health`, 3e3));
10893
+ var DEFAULT_CLI_URL = `http://localhost:${DEFAULT_APP_PORT}`;
10894
+ var offerCliHere = async (runtime, options, existing, config, instance) => {
10895
+ if (runtime.savedCliLogin === void 0) return null;
10896
+ const saved = runtime.savedCliLogin(runtime.configDir);
10897
+ if (runtime.repointCliLogin === void 0) return saved;
10898
+ const url = saved?.url ?? DEFAULT_CLI_URL;
10899
+ const there = await healthAt(runtime, url);
10900
+ if (isThisInstall(there, config.serverVersion, instance)) return saved;
10901
+ const signedIn = saved?.signedIn === true;
10902
+ const keepSignIn = signedIn && there.kind === "other" && existing !== null;
10903
+ const preferred = !(signedIn && there.kind === "mend");
10904
+ const what = there.kind === "mend" ? `another Mend, ${there.version}, answers` : "nothing answers";
10905
+ const signIn = keepSignIn ? " Its sign-in carries over." : signedIn ? ` Its sign-in at ${url} stays behind.` : "";
10906
+ let move = options.yes && preferred;
10907
+ if (!options.yes && runtime.prompter !== void 0) {
10908
+ const answer2 = await runtime.prompter(
10909
+ `This machine's CLI points at ${url}, where ${what}. Point it at ${config.appUrl}?${signIn} ${preferred ? "[Y/n]" : "[y/N]"} `
10910
+ );
10911
+ const given = answer2?.trim() ?? "";
10912
+ move = answer2 !== null && (given === "" ? preferred : /^y/i.test(given));
10538
10913
  }
10914
+ if (!move) return saved;
10915
+ runtime.repointCliLogin(runtime.configDir, config.appUrl, { keepSignIn });
10916
+ runtime.writeLine(
10917
+ `This machine's CLI now points at ${config.appUrl}${keepSignIn ? "; its sign-in carried over" : ""}.`
10918
+ );
10919
+ return { url: config.appUrl, signedIn: keepSignIn };
10539
10920
  };
10540
10921
  var reachedBefore = (url, before) => {
10541
10922
  let parsed;
@@ -10549,12 +10930,12 @@ var reachedBefore = (url, before) => {
10549
10930
  const port = parsed.port === "" ? parsed.protocol === "https:" ? 443 : 80 : Number(parsed.port);
10550
10931
  return isLoopbackHost(parsed.hostname) && port === before.appPort && (isLoopbackBind(before.bind) || before.bind === "0.0.0.0" || before.bind === "::");
10551
10932
  };
10552
- var followUrlChange = async (runtime, options, before, after) => {
10933
+ var followUrlChange = async (runtime, options, before, after, instance) => {
10553
10934
  runtime.writeLine(
10554
- `Mend's URL changed from ${before.appUrl} to ${after.appUrl}. Browsers open ${after.appUrl}. A CLI signed in at the old URL (another account on this machine, another machine) moves with: mend login --url ${after.appUrl}`
10935
+ `Mend's URL changed from ${before.appUrl} to ${after.appUrl}. Browsers open ${after.appUrl}. A CLI signed in at the old URL (another account on this machine, another machine) signs in again with mend login --url ${after.appUrl}, which asks for a new browser authorization.`
10555
10936
  );
10556
10937
  const saved = runtime.savedCliLogin?.(runtime.configDir) ?? null;
10557
- if (saved === null || !saved.signedIn || !reachedBefore(saved.url, before) || await answersAs(runtime, saved.url, after.serverVersion)) {
10938
+ if (saved === null || !saved.signedIn || !reachedBefore(saved.url, before) || await answersAs(runtime, saved.url, after.serverVersion, instance)) {
10558
10939
  return saved;
10559
10940
  }
10560
10941
  let move = options.yes;
@@ -10646,7 +11027,7 @@ var startInstallation = async (runtime, installation, secrets) => {
10646
11027
  "--no-build"
10647
11028
  ]);
10648
11029
  await initGarage(runtime, installation, secrets);
10649
- await probeHealth(runtime, healthOrigin(installation.config), installation.config.serverVersion);
11030
+ await probeHealth(runtime, installation.config, instanceIdOf(secrets.betterAuthSecret));
10650
11031
  runtime.writeLine(reachableLine(installation.config));
10651
11032
  };
10652
11033
  var DEFAULT_KEEP_BACKUPS = 2;
@@ -11294,7 +11675,7 @@ var manageServer = async (command, args, runtime, store) => {
11294
11675
  };
11295
11676
  var nodeServerRuntime = () => {
11296
11677
  const environment = { ...process.env };
11297
- const home = os10.homedir();
11678
+ const home = os9.homedir();
11298
11679
  const configHome = environment["XDG_CONFIG_HOME"] ?? path16.join(home, ".config");
11299
11680
  return {
11300
11681
  configDir: path16.join(configHome, "mend"),
@@ -11326,6 +11707,7 @@ var nodeServerRuntime = () => {
11326
11707
  repointCliLogin: repointCliLoginHere,
11327
11708
  probeSsh: probeSshFromHere,
11328
11709
  portTaken: portTakenHere,
11710
+ ...environment["DOCKER_CONTEXT"] === void 0 || environment["DOCKER_CONTEXT"].trim() === "" ? {} : { dockerContextVariable: environment["DOCKER_CONTEXT"].trim() },
11329
11711
  ...process.stdin.isTTY === true && process.stdout.isTTY === true ? { prompter: askOnTerminal } : {},
11330
11712
  lookupHost: async (host) => {
11331
11713
  try {
@@ -11334,8 +11716,7 @@ var nodeServerRuntime = () => {
11334
11716
  return null;
11335
11717
  }
11336
11718
  },
11337
- // Container and VM bridges (Docker's own among them) are never where people reach Mend.
11338
- localAddresses: () => Object.entries(os10.networkInterfaces()).filter(([name]) => !/^(docker|br-|veth|virbr|cni|flannel|vmnet|vboxnet)/.test(name)).flatMap(([, entries]) => entries ?? []).filter((entry) => !entry.internal).map((entry) => entry.address),
11719
+ localAddresses: () => reachableAddressesOf(os9.networkInterfaces()),
11339
11720
  readStdin: async () => {
11340
11721
  const chunks = [];
11341
11722
  for await (const chunk of process.stdin)
@@ -11380,14 +11761,36 @@ var sshBannerAt = async (host, port, timeoutMs) => {
11380
11761
  socket.destroy();
11381
11762
  }
11382
11763
  };
11383
- var portTakenHere = (port) => new Promise((resolve8) => {
11384
- const server = net4.createServer();
11385
- server.once("error", (error) => resolve8(error.code === "EADDRINUSE"));
11386
- server.listen(port, "127.0.0.1", () => server.close(() => resolve8(false)));
11387
- });
11764
+ var BRIDGE_INTERFACE = /^(docker|br-|veth|virbr|cni|flannel|vmnet|vboxnet|bridge\d)/;
11765
+ var ipv4Value = (address) => address.split(".").reduce((sum, octet) => sum * 256 + Number(octet), 0);
11766
+ var isNetworkAddress = (entry) => {
11767
+ if (entry.family !== "IPv4") return false;
11768
+ if (entry.address.endsWith(".0")) return true;
11769
+ const prefix = Number(entry.cidr?.split("/")[1] ?? "32");
11770
+ return prefix < 31 && ipv4Value(entry.address) % 2 ** (32 - prefix) === 0;
11771
+ };
11772
+ var reachableAddressesOf = (interfaces) => Object.entries(interfaces).filter(([name]) => !BRIDGE_INTERFACE.test(name)).flatMap(([, entries]) => entries ?? []).filter((entry) => !entry.internal && !isNetworkAddress(entry)).map((entry) => entry.address);
11773
+ var portTakenHere = async (port, address = "127.0.0.1") => {
11774
+ const bindFails = await new Promise((resolve8) => {
11775
+ const server = net4.createServer();
11776
+ server.once("error", (error) => resolve8(error.code === "EADDRINUSE"));
11777
+ server.listen(port, address, () => server.close(() => resolve8(false)));
11778
+ });
11779
+ if (bindFails) return true;
11780
+ return new Promise((resolve8) => {
11781
+ const socket = net4.connect({ host: connectHost(address), port });
11782
+ const done = (answered) => {
11783
+ socket.destroy();
11784
+ resolve8(answered);
11785
+ };
11786
+ socket.setTimeout(1e3, () => done(false));
11787
+ socket.once("connect", () => done(true));
11788
+ socket.once("error", () => done(false));
11789
+ });
11790
+ };
11388
11791
  var probeSshFromHere = async (bind, port) => {
11389
11792
  const unspecified = bind === "0.0.0.0" || bind === "::";
11390
- const addresses = unspecified ? Object.values(os10.networkInterfaces()).flatMap((entries) => entries ?? []).filter(
11793
+ const addresses = unspecified ? Object.values(os9.networkInterfaces()).flatMap((entries) => entries ?? []).filter(
11391
11794
  (entry) => !entry.internal && (entry.family === "IPv4" || bind === "::" && !entry.address.startsWith("fe80"))
11392
11795
  ).map((entry) => entry.address).slice(0, 4) : [bind];
11393
11796
  return Promise.all(
@@ -11423,11 +11826,15 @@ var savedCliLoginHere = (configDir) => {
11423
11826
  const token = fields?.get("token");
11424
11827
  return typeof url === "string" ? { url, signedIn: typeof token === "string" && token !== "" } : null;
11425
11828
  };
11426
- var repointCliLoginHere = (configDir, url) => {
11427
- const fields = cliJsonFields(configDir);
11428
- if (fields === null) return;
11829
+ var repointCliLoginHere = (configDir, url, options = { keepSignIn: true }) => {
11429
11830
  const file = path16.join(configDir, "cli.json");
11430
- fs16.writeFileSync(file, `${JSON.stringify({ ...Object.fromEntries(fields), url }, null, 2)}
11831
+ const fields = cliJsonFields(configDir) ?? (fs16.existsSync(file) ? null : /* @__PURE__ */ new Map());
11832
+ if (fields === null) return;
11833
+ const kept = [...fields].filter(
11834
+ ([key]) => options.keepSignIn || key !== "token" && key !== "deviceId"
11835
+ );
11836
+ fs16.mkdirSync(configDir, { recursive: true, mode: 448 });
11837
+ fs16.writeFileSync(file, `${JSON.stringify({ ...Object.fromEntries(kept), url }, null, 2)}
11431
11838
  `, {
11432
11839
  mode: 384
11433
11840
  });
@@ -11442,7 +11849,8 @@ var serverCommand = async (args, runtime = nodeServerRuntime()) => {
11442
11849
  };
11443
11850
  }
11444
11851
  try {
11445
- if (command === "setup" && rest.every((arg) => HOST_FLAGS.has(arg)) && runtime.prompter !== void 0) {
11852
+ if (command === "setup" && answersNoQuestion(rest) && runtime.prompter !== void 0) {
11853
+ parseSetupOptions(rest);
11446
11854
  return await guidedSetup(runtime, runtime.prompter, rest);
11447
11855
  }
11448
11856
  return await underLock(
@@ -11928,17 +12336,17 @@ var scanSkillLibrary = (root) => {
11928
12336
  const files = [];
11929
12337
  let bytes = 0;
11930
12338
  for (const absolute of walkFiles(skillDir)) {
11931
- const relative5 = path17.relative(skillDir, absolute).split(path17.sep).join("/");
12339
+ const relative6 = path17.relative(skillDir, absolute).split(path17.sep).join("/");
11932
12340
  const buffer = fs17.readFileSync(absolute);
11933
12341
  if (buffer.byteLength > MAX_SKILL_FILE_BYTES) {
11934
- notes.push({ skill: entry.name, message: `${relative5} is over 512KB \u2014 skipped` });
12342
+ notes.push({ skill: entry.name, message: `${relative6} is over 512KB \u2014 skipped` });
11935
12343
  continue;
11936
12344
  }
11937
12345
  if (!isTextBuffer(buffer)) {
11938
- notes.push({ skill: entry.name, message: `${relative5} is binary \u2014 skipped` });
12346
+ notes.push({ skill: entry.name, message: `${relative6} is binary \u2014 skipped` });
11939
12347
  continue;
11940
12348
  }
11941
- files.push({ path: relative5, contents: buffer.toString("utf8") });
12349
+ files.push({ path: relative6, contents: buffer.toString("utf8") });
11942
12350
  bytes += buffer.byteLength;
11943
12351
  }
11944
12352
  if (files.length > MAX_SKILL_FILES) {
@@ -11965,15 +12373,15 @@ var scanSkillLibrary = (root) => {
11965
12373
 
11966
12374
  // src/ssh-setup.ts
11967
12375
  import * as fs19 from "node:fs";
11968
- import * as os12 from "node:os";
12376
+ import * as os11 from "node:os";
11969
12377
  import * as path19 from "node:path";
11970
12378
 
11971
12379
  // ../../packages/workspace-ssh/src/index.ts
11972
- import { spawnSync as spawnSync5 } from "node:child_process";
12380
+ import { spawnSync as spawnSync6 } from "node:child_process";
11973
12381
  import { createHash as createHash3 } from "node:crypto";
11974
12382
  import * as fs18 from "node:fs";
11975
12383
  import { isIP as isIP3 } from "node:net";
11976
- import * as os11 from "node:os";
12384
+ import * as os10 from "node:os";
11977
12385
  import * as path18 from "node:path";
11978
12386
  var LEGACY_BLOCK_BEGIN = "# >>> mend workspace ssh (managed by `mend ssh setup`) >>>";
11979
12387
  var LEGACY_BLOCK_END = "# <<< mend workspace ssh <<<";
@@ -12062,7 +12470,7 @@ var blockEnd = (alias) => `# <<< mend workspace ssh ${alias} <<<`;
12062
12470
  var hasControls = (value) => /[\p{Cc}\p{Zl}\p{Zp}]/u.test(value);
12063
12471
  var parseIdentityPath = (value) => {
12064
12472
  const resolved = path18.resolve(
12065
- value.startsWith("~/") ? path18.join(os11.homedir(), value.slice(2)) : value
12473
+ value.startsWith("~/") ? path18.join(os10.homedir(), value.slice(2)) : value
12066
12474
  );
12067
12475
  if (value === "" || hasControls(value) || hasControls(resolved) || value.includes("${") || resolved.includes("${")) {
12068
12476
  return failure(
@@ -12142,25 +12550,80 @@ var removeManagedBlock = (config, beginMarker, endMarker) => {
12142
12550
  }
12143
12551
  return success(`${config.slice(0, begin)}${after}`);
12144
12552
  };
12145
- var stripManagedWorkspaceSshBlocks = (existing) => {
12553
+ var LEGACY_ALIAS = "mend-ws";
12554
+ var decodeIdentityFile = (value) => {
12555
+ if (value === void 0) return null;
12556
+ if (!value.startsWith('"')) return value;
12557
+ if (!/^"(?:[^"\\]|\\["\\])*"$/.test(value)) return null;
12558
+ return value.slice(1, -1).replace(/\\(["\\])/g, "$1").replaceAll("%%", "%");
12559
+ };
12560
+ var blockFacts = (body, alias, legacy) => {
12561
+ const directive = (name) => new RegExp(`^\\s*${name}\\s+(.+?)\\s*$`, "im").exec(body)?.[1];
12562
+ const port = Number(directive("Port"));
12563
+ return {
12564
+ alias,
12565
+ legacy,
12566
+ hostname: directive("HostName") ?? null,
12567
+ port: Number.isInteger(port) && port > 0 ? port : null,
12568
+ identityFile: decodeIdentityFile(directive("IdentityFile"))
12569
+ };
12570
+ };
12571
+ var blockBody = (config, beginMarker, endMarker) => {
12572
+ const begin = config.indexOf(beginMarker);
12573
+ if (begin === -1) return null;
12574
+ const end = config.indexOf(endMarker, begin + beginMarker.length);
12575
+ return end === -1 ? null : config.slice(begin + beginMarker.length, end);
12576
+ };
12577
+ var listManagedWorkspaceSshBlocks = (config) => {
12578
+ const aliases = new Set(
12579
+ [...config.matchAll(/^# >>> mend workspace ssh (mend-ws-[a-z0-9-]+) \(managed\) >>>$/gm)].map((match) => match[1]).filter((alias) => alias !== void 0)
12580
+ );
12581
+ const blocks = [];
12582
+ for (const alias of aliases) {
12583
+ const body = blockBody(config, blockBegin(alias), blockEnd(alias));
12584
+ if (body !== null) blocks.push(blockFacts(body, alias, false));
12585
+ }
12586
+ const legacy = blockBody(config, LEGACY_BLOCK_BEGIN, LEGACY_BLOCK_END);
12587
+ if (legacy !== null) blocks.push(blockFacts(legacy, LEGACY_ALIAS, true));
12588
+ return blocks;
12589
+ };
12590
+ var workspaceSshAlias = (serverUrl) => {
12591
+ const target = parseWorkspaceSshTarget({ serverUrl, publishedPort: 22 });
12592
+ return target.ok ? target.value.alias : null;
12593
+ };
12594
+ var stripManagedWorkspaceSshBlocks = (existing, owned) => {
12146
12595
  let config = existing;
12147
- let removed = 0;
12148
- const aliases = [
12149
- ...config.matchAll(/^# >>> mend workspace ssh (mend-ws-[a-z0-9-]+) \(managed\) >>>$/gm)
12150
- ].map((match) => match[1]).filter((alias) => alias !== void 0);
12151
- for (const alias of new Set(aliases)) {
12152
- const stripped = removeManagedBlock(config, blockBegin(alias), blockEnd(alias));
12596
+ const removed = [];
12597
+ const kept = [];
12598
+ let legacy = null;
12599
+ for (const block of listManagedWorkspaceSshBlocks(existing)) {
12600
+ if (block.legacy) {
12601
+ legacy = block;
12602
+ continue;
12603
+ }
12604
+ if (!owned(block)) {
12605
+ kept.push(block);
12606
+ continue;
12607
+ }
12608
+ const stripped = removeManagedBlock(config, blockBegin(block.alias), blockEnd(block.alias));
12153
12609
  if (!stripped.ok) return stripped;
12154
12610
  config = stripped.value;
12155
- removed += 1;
12611
+ removed.push(block);
12156
12612
  }
12157
- if (config.includes(LEGACY_BLOCK_BEGIN)) {
12158
- const stripped = removeManagedBlock(config, LEGACY_BLOCK_BEGIN, LEGACY_BLOCK_END);
12159
- if (!stripped.ok) return stripped;
12160
- config = stripped.value;
12161
- removed += 1;
12613
+ for (const alias of config.matchAll(
12614
+ /^# >>> mend workspace ssh (mend-ws-[a-z0-9-]+) \(managed\) >>>$/gm
12615
+ )) {
12616
+ const name = alias[1] ?? "";
12617
+ if (blockBody(config, blockBegin(name), blockEnd(name)) === null) {
12618
+ return failure(
12619
+ new WorkspaceSshError(
12620
+ "config",
12621
+ `Managed SSH config block beginning with "${blockBegin(name)}" has no closing marker.`
12622
+ )
12623
+ );
12624
+ }
12162
12625
  }
12163
- return success({ config, removed });
12626
+ return success({ config, removed, kept, legacy });
12164
12627
  };
12165
12628
  var containsExactHost = (config, alias) => config.split("\n").some((line) => {
12166
12629
  const match = /^\s*Host\s+(.+?)\s*$/i.exec(line);
@@ -12173,11 +12636,9 @@ var reconcileWorkspaceSshConfig = (existing, target, identityFile) => {
12173
12636
  blockEnd(target.alias)
12174
12637
  );
12175
12638
  if (!withoutCurrent.ok) return withoutCurrent;
12176
- const withoutLegacy = removeManagedBlock(
12177
- withoutCurrent.value,
12178
- LEGACY_BLOCK_BEGIN,
12179
- LEGACY_BLOCK_END
12180
- );
12639
+ const legacy = listManagedWorkspaceSshBlocks(withoutCurrent.value).find((block2) => block2.legacy);
12640
+ const legacyIsThisServer = legacy === void 0 || legacy.hostname?.toLowerCase() === target.hostname.toLowerCase() && (legacy.port ?? 22) === target.port;
12641
+ const withoutLegacy = legacyIsThisServer ? removeManagedBlock(withoutCurrent.value, LEGACY_BLOCK_BEGIN, LEGACY_BLOCK_END) : withoutCurrent;
12181
12642
  if (!withoutLegacy.ok) return withoutLegacy;
12182
12643
  if (containsExactHost(withoutLegacy.value, target.alias)) {
12183
12644
  return failure(
@@ -12208,7 +12669,7 @@ var workspaceSshPublicKeyFingerprint = (publicKey) => {
12208
12669
  var publicKeyIdentity = (publicKey) => publicKey.trim().split(/\s+/).slice(0, 2).join(" ");
12209
12670
  var agentKeys = () => {
12210
12671
  if (!process.env["SSH_AUTH_SOCK"]) return [];
12211
- const listed3 = spawnSync5("ssh-add", ["-L"], {
12672
+ const listed3 = spawnSync6("ssh-add", ["-L"], {
12212
12673
  encoding: "utf8",
12213
12674
  timeout: 3e3,
12214
12675
  stdio: ["ignore", "pipe", "pipe"],
@@ -12225,17 +12686,8 @@ var readText = (file) => {
12225
12686
  }
12226
12687
  };
12227
12688
  var configuredWorkspaceSshIdentityFile = (config, target) => {
12228
- const begin = config.indexOf(blockBegin(target.alias));
12229
- if (begin === -1) return null;
12230
- const end = config.indexOf(blockEnd(target.alias), begin);
12231
- if (end === -1) return null;
12232
- const block = config.slice(begin, end);
12233
- const match = /^\s*IdentityFile\s+(.+?)\s*$/m.exec(block);
12234
- const value = match?.[1];
12235
- if (value === void 0) return null;
12236
- if (!value.startsWith('"')) return value;
12237
- if (!/^"(?:[^"\\]|\\["\\])*"$/.test(value)) return null;
12238
- return value.slice(1, -1).replace(/\\(["\\])/g, "$1").replaceAll("%%", "%");
12689
+ const body = blockBody(config, blockBegin(target.alias), blockEnd(target.alias));
12690
+ return body === null ? null : blockFacts(body, target.alias, false).identityFile;
12239
12691
  };
12240
12692
  var publicKeyPath = (keyPath) => keyPath.endsWith(".pub") ? keyPath : `${keyPath}.pub`;
12241
12693
  var readRequiredKey = (keyPath, source) => {
@@ -12245,7 +12697,7 @@ var readRequiredKey = (keyPath, source) => {
12245
12697
  const privatePath = publicPath.slice(0, -".pub".length);
12246
12698
  const read = readText(publicPath);
12247
12699
  if (!read.ok) return read;
12248
- const derived = spawnSync5("ssh-keygen", ["-y", "-P", "", "-f", privatePath], {
12700
+ const derived = spawnSync6("ssh-keygen", ["-y", "-P", "", "-f", privatePath], {
12249
12701
  encoding: "utf8",
12250
12702
  timeout: 3e3,
12251
12703
  stdio: ["ignore", "pipe", "pipe"],
@@ -12305,9 +12757,9 @@ var generateDedicatedKey = (privatePath) => {
12305
12757
  new WorkspaceSshError("key", `Could not create ${path18.dirname(privatePath)}.`, cause)
12306
12758
  );
12307
12759
  }
12308
- const generated = spawnSync5(
12760
+ const generated = spawnSync6(
12309
12761
  "ssh-keygen",
12310
- ["-t", "ed25519", "-f", privatePath, "-N", "", "-C", `mend-${os11.hostname()}`],
12762
+ ["-t", "ed25519", "-f", privatePath, "-N", "", "-C", `mend-${os10.hostname()}`],
12311
12763
  { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "pipe"] }
12312
12764
  );
12313
12765
  if (generated.status !== 0) {
@@ -12449,8 +12901,8 @@ var dim5 = ansi("2");
12449
12901
  var green5 = ansi("32");
12450
12902
  var warn = ansi("33");
12451
12903
  var say5 = (line) => console.log(redactCredentials(line));
12452
- var sshConfigPath = () => path19.join(os12.homedir(), ".ssh", "config");
12453
- var flagValue2 = (args, flag) => {
12904
+ var sshConfigPath = () => path19.join(os11.homedir(), ".ssh", "config");
12905
+ var flagValue = (args, flag) => {
12454
12906
  const index = args.indexOf(flag);
12455
12907
  return index === -1 || args[index + 1] === void 0 ? null : String(args[index + 1]);
12456
12908
  };
@@ -12467,7 +12919,7 @@ var showStatus = async (api2, cliHome, serverUrl, args) => {
12467
12919
  const parsedTarget = parseWorkspaceSshTarget({
12468
12920
  serverUrl,
12469
12921
  publishedPort: view.gateway.port,
12470
- hostnameOverride: flagValue2(args, "--host")
12922
+ hostnameOverride: flagValue(args, "--host")
12471
12923
  });
12472
12924
  if (parsedTarget.ok === false) return showFailure(parsedTarget.error.message);
12473
12925
  const config = readWorkspaceSshConfig(sshConfigPath());
@@ -12504,14 +12956,14 @@ var setup = async (api2, cliHome, serverUrl, args) => {
12504
12956
  const parsedTarget = parseWorkspaceSshTarget({
12505
12957
  serverUrl,
12506
12958
  publishedPort: view.gateway.port,
12507
- hostnameOverride: flagValue2(args, "--host")
12959
+ hostnameOverride: flagValue(args, "--host")
12508
12960
  });
12509
12961
  if (parsedTarget.ok === false) return showFailure(parsedTarget.error.message);
12510
12962
  const config = readWorkspaceSshConfig(sshConfigPath());
12511
12963
  if (config.ok === false) return showFailure(config.error.message);
12512
12964
  const picked = pickWorkspaceSshKey({
12513
12965
  configHome: cliHome,
12514
- explicitKeyPath: flagValue2(args, "--key"),
12966
+ explicitKeyPath: flagValue(args, "--key"),
12515
12967
  configuredIdentityFile: configuredWorkspaceSshIdentityFile(config.value, parsedTarget.value),
12516
12968
  create: true
12517
12969
  });
@@ -12519,7 +12971,7 @@ var setup = async (api2, cliHome, serverUrl, args) => {
12519
12971
  if (picked.value === null) return showFailure("No workspace SSH key is available.");
12520
12972
  const registered = await api2("POST", "/workspace-ssh/keys", {
12521
12973
  publicKey: picked.value.publicKey,
12522
- name: os12.hostname()
12974
+ name: os11.hostname()
12523
12975
  });
12524
12976
  const sourceLabel = {
12525
12977
  explicit: "from --key",
@@ -12542,9 +12994,53 @@ var setup = async (api2, cliHome, serverUrl, args) => {
12542
12994
  );
12543
12995
  say5("");
12544
12996
  say5(
12545
- `connect with ssh ${view.gateway.usernamePrefix}-<workspace-id>@${parsedTarget.value.alias} ${dim5("\xB7 the VS Code extension uses this automatically")}`
12997
+ `connect with mend ssh <session> ${dim5(`\xB7 prints the ssh command for one session's workspace (ssh ${view.gateway.usernamePrefix}-<workspace>@${parsedTarget.value.alias}); the VS Code extension connects by itself`)}`
12546
12998
  );
12547
12999
  };
13000
+ var workspaceSshCommand = (usernamePrefix, workspaceId, alias) => `ssh ${usernamePrefix}-${workspaceId}@${alias}`;
13001
+ var sessionSsh = async (api2, cliHome, serverUrl, session, args) => {
13002
+ const id8 = session.id.slice(0, 8);
13003
+ const workspaceId = session.sealantWorkspaceId ?? null;
13004
+ if (workspaceId === null) {
13005
+ return showFailure(
13006
+ `session ${id8} has no running workspace to ssh into (${session.status}) \xB7 resume the session, then run mend ssh ${id8} again`
13007
+ );
13008
+ }
13009
+ const view = await api2("GET", "/workspace-ssh");
13010
+ if (view.gateway === null)
13011
+ return showFailure("This deployment exposes no workspace SSH gateway.");
13012
+ const parsedTarget = parseWorkspaceSshTarget({
13013
+ serverUrl,
13014
+ publishedPort: view.gateway.port,
13015
+ hostnameOverride: flagValue(args, "--host")
13016
+ });
13017
+ if (parsedTarget.ok === false) return showFailure(parsedTarget.error.message);
13018
+ console.log(
13019
+ workspaceSshCommand(view.gateway.usernamePrefix, workspaceId, parsedTarget.value.alias)
13020
+ );
13021
+ const config = readWorkspaceSshConfig(sshConfigPath());
13022
+ const picked = config.ok === false ? null : pickWorkspaceSshKey({
13023
+ configHome: cliHome,
13024
+ configuredIdentityFile: configuredWorkspaceSshIdentityFile(
13025
+ config.value,
13026
+ parsedTarget.value
13027
+ ),
13028
+ create: false
13029
+ });
13030
+ const ready = config.ok && picked !== null && picked.ok && inspectWorkspaceSshReadiness({
13031
+ config: config.value,
13032
+ target: parsedTarget.value,
13033
+ key: picked.value,
13034
+ registeredFingerprints: view.keys.map((key) => key.fingerprint)
13035
+ }).ready;
13036
+ if (!ready) {
13037
+ console.error(
13038
+ redactCredentials(
13039
+ `${warn("not set up")} ${dim5(`\xB7 this machine has no ready Host ${parsedTarget.value.alias} block or registered key \xB7 run: mend ssh setup`)}`
13040
+ )
13041
+ );
13042
+ }
13043
+ };
12548
13044
  var errorText = (cause) => cause instanceof Error ? cause.message : String(cause);
12549
13045
  var thisMachineKeys = (view, cliHome, serverUrl) => {
12550
13046
  const fingerprints = /* @__PURE__ */ new Set();
@@ -12723,7 +13219,7 @@ var keysCommand = async (api2, cliHome, serverUrl, args) => {
12723
13219
  );
12724
13220
  }
12725
13221
  };
12726
- var sshCommand = async (args, api2, cliHome, serverUrl) => {
13222
+ var sshCommand = async (args, api2, cliHome, serverUrl, findSession2) => {
12727
13223
  const [subcommand, ...rest] = args;
12728
13224
  switch (subcommand) {
12729
13225
  case void 0:
@@ -12734,14 +13230,18 @@ var sshCommand = async (args, api2, cliHome, serverUrl) => {
12734
13230
  case "keys":
12735
13231
  return keysCommand(api2, cliHome, serverUrl, rest);
12736
13232
  default:
13233
+ if (/^[0-9a-f][0-9a-f-]*$/i.test(subcommand)) {
13234
+ return sessionSsh(api2, cliHome, serverUrl, await findSession2(subcommand), rest);
13235
+ }
12737
13236
  showFailure(
12738
- `Unknown ssh subcommand "${subcommand}". Try: mend ssh \xB7 mend ssh setup [--key <path>] [--host <hostname>] \xB7 mend ssh keys [remove <fingerprint>]`
13237
+ `Unknown ssh subcommand "${subcommand}". Try: mend ssh \xB7 mend ssh <session> \xB7 mend ssh setup [--key <path>] [--host <hostname>] \xB7 mend ssh keys [remove <fingerprint>]`
12739
13238
  );
12740
13239
  }
12741
13240
  };
12742
13241
 
12743
13242
  // src/uninstall.ts
12744
13243
  import * as fs20 from "node:fs";
13244
+ import * as os12 from "node:os";
12745
13245
  import * as path20 from "node:path";
12746
13246
  var UNINSTALL_USAGE = "usage: mend uninstall [--all | --server | --home] [--yes]";
12747
13247
  var parseUninstallArgs = (args) => {
@@ -12811,16 +13311,26 @@ var exists = (file) => {
12811
13311
  return false;
12812
13312
  }
12813
13313
  };
12814
- var managedBlockCount = (sshConfigFile) => {
12815
- let config;
13314
+ var readSshBlocks = (sshConfigFile) => {
12816
13315
  try {
12817
- config = fs20.readFileSync(sshConfigFile, "utf8");
13316
+ return listManagedWorkspaceSshBlocks(fs20.readFileSync(sshConfigFile, "utf8"));
12818
13317
  } catch {
12819
- return 0;
13318
+ return [];
12820
13319
  }
12821
- const stripped = stripManagedWorkspaceSshBlocks(config);
12822
- return stripped.ok ? stripped.value.removed : 0;
12823
13320
  };
13321
+ var sshBlockOwned = (owners) => (block) => {
13322
+ if (block.legacy) return false;
13323
+ if (owners.urls.some((url) => workspaceSshAlias(url) === block.alias)) return true;
13324
+ const { gateway } = owners;
13325
+ return gateway !== null && block.port === gateway.port && block.hostname !== null && gateway.hosts.includes(block.hostname.toLowerCase());
13326
+ };
13327
+ var blockLabel = (block) => `Host ${block.alias}${block.hostname === null ? "" : ` \u2192 ${block.hostname}${block.port === null ? "" : `:${block.port}`}`}`;
13328
+ var within = (directory, file) => {
13329
+ const resolved = file.startsWith("~/") ? path20.join(os12.homedir(), file.slice(2)) : file;
13330
+ const relative6 = path20.relative(directory, resolved);
13331
+ return relative6 !== "" && !relative6.startsWith("..") && !path20.isAbsolute(relative6);
13332
+ };
13333
+ var legacyBlockNote = (block, sshConfigFile) => `${sshConfigFile}: ${blockLabel(block)} stays. An older mend ssh setup wrote it, and nothing in it says which server it is for. If it is this one's, delete it from the line "# >>> mend workspace ssh (managed by \`mend ssh setup\`) >>>" to "# <<< mend workspace ssh <<<"`;
12824
13334
  var plural = (count, noun) => `${count} ${noun}${count === 1 ? "" : "s"}`;
12825
13335
  var listOf = (names, shown = 3) => `${names.slice(0, shown).join(", ")}${names.length > shown ? `, and ${names.length - shown} more` : ""}`;
12826
13336
  var formatBytes5 = (bytes) => {
@@ -12890,14 +13400,17 @@ var findWorkspaces = async (run2, context, controlVolume) => {
12890
13400
  "--filter",
12891
13401
  `volume=${controlVolume}`,
12892
13402
  "--format",
12893
- "{{.Names}} {{.State}} {{.Image}}"
13403
+ '{{.Names}} {{.State}} {{.Image}} {{.Label "com.docker.compose.project"}}'
12894
13404
  ]);
12895
13405
  if (mounted.status !== 0) return { problem: detail(mounted) };
12896
- const workspaces = rows(mounted.stdout).flatMap(
13406
+ const sessionRows = rows(mounted.stdout).filter(
13407
+ ([, , , project2]) => project2 !== MEND_DOCKER_NAMESPACE.project
13408
+ );
13409
+ const workspaces = sessionRows.flatMap(
12897
13410
  ([name, state]) => name !== void 0 && DOCKER_NAME.test(name) ? [{ name, running: state === "running" }] : []
12898
13411
  );
12899
13412
  const images = new Set(
12900
- rows(mounted.stdout).flatMap(
13413
+ sessionRows.flatMap(
12901
13414
  ([, , image]) => image !== void 0 && IMAGE_REFERENCE2.test(image) ? [image] : []
12902
13415
  )
12903
13416
  );
@@ -12928,6 +13441,60 @@ var findWorkspaces = async (run2, context, controlVolume) => {
12928
13441
  images: [...images]
12929
13442
  };
12930
13443
  };
13444
+ var serverServices = (plan) => [
13445
+ "mend",
13446
+ "postgres",
13447
+ "garage",
13448
+ ...plan.edgeHost == null ? [] : ["edge"],
13449
+ ...plan.mirrors ?? []
13450
+ ];
13451
+ var composeServices = async (run2, target) => {
13452
+ const listed3 = await run2("docker", serverComposeArgs(target, ["ps", "--all", "--services"]), {
13453
+ timeoutMs: DOCKER_DEADLINE_MS
13454
+ });
13455
+ if (listed3.status !== 0) return null;
13456
+ const order = ["mend", "postgres", "garage", "edge", "npm-mirror", "docker-mirror"];
13457
+ const rank = (service) => {
13458
+ const at = order.indexOf(service);
13459
+ return at === -1 ? order.length : at;
13460
+ };
13461
+ return [
13462
+ ...new Set(
13463
+ rows(listed3.stdout).map(([service]) => service ?? "").filter((service) => DOCKER_NAME.test(service))
13464
+ )
13465
+ ].toSorted((a, b) => rank(a) - rank(b));
13466
+ };
13467
+ var serverVolumes = (plan) => [
13468
+ MEND_DOCKER_NAMESPACE_WITH_GARAGE.store,
13469
+ ...secondaryVolumesOf(MEND_DOCKER_NAMESPACE_WITH_GARAGE),
13470
+ "mend-config",
13471
+ "mend-ssh",
13472
+ "mend-postgres",
13473
+ ...plan.edgeHost === null ? [] : ["mend-edge-data", "mend-edge-config"],
13474
+ ...(plan.mirrors ?? []).map((service) => `mend-${service}`),
13475
+ // The t3code gateway's state, with paired people's device tokens, when it is there.
13476
+ ...plan.t3GatewayVolume === true ? [T3_GATEWAY_VOLUME] : []
13477
+ ];
13478
+ var serverPresent = async (run2, target, volumes, image) => {
13479
+ const containers = await composeServices(run2, target);
13480
+ const listed3 = await listNamesIn(run2, target.dockerContext, "volume", []);
13481
+ if (containers === null || "problem" in listed3) return void 0;
13482
+ const inspected = await dockerIn(run2, target.dockerContext, [
13483
+ "image",
13484
+ "inspect",
13485
+ image,
13486
+ "--format",
13487
+ "{{.Id}}"
13488
+ ]);
13489
+ return {
13490
+ containers,
13491
+ volumes: volumes.filter(
13492
+ (name) => listed3.includes(name) || listed3.includes(`${MEND_DOCKER_NAMESPACE.project}_${name}`)
13493
+ ),
13494
+ // Unknown is not gone: only Docker saying there is no such image leaves it out.
13495
+ image: inspected.status === 0 || !notFound(inspected)
13496
+ };
13497
+ };
12931
13498
  var readLeft = (configDir) => {
12932
13499
  try {
12933
13500
  const parsed = JSON.parse(fs20.readFileSync(path20.join(configDir, LEFT_FILE), "utf8"));
@@ -13070,7 +13637,7 @@ var parseUrl2 = (value) => {
13070
13637
  }
13071
13638
  };
13072
13639
  var isLoopback = (host) => ["localhost", "127.0.0.1", "[::1]", "::1"].includes(host);
13073
- var portOf = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
13640
+ var portOf2 = (url) => url.port || (url.protocol === "https:" ? "443" : "80");
13074
13641
  var signedInTo = (signedInUrl, appUrl, edgeHost) => {
13075
13642
  const signed = parseUrl2(signedInUrl);
13076
13643
  if (signed === null) return false;
@@ -13079,7 +13646,7 @@ var signedInTo = (signedInUrl, appUrl, edgeHost) => {
13079
13646
  const app = parseUrl2(appUrl);
13080
13647
  if (app === null) return false;
13081
13648
  if (signed.origin === app.origin) return true;
13082
- return isLoopback(signed.hostname) && portOf(signed) === portOf(app);
13649
+ return isLoopback(signed.hostname) && portOf2(signed) === portOf2(app);
13083
13650
  };
13084
13651
  var describeUninstall = async (runtime, scope) => {
13085
13652
  let server = null;
@@ -13116,8 +13683,19 @@ var describeUninstall = async (runtime, scope) => {
13116
13683
  let holdings = NO_HOLDINGS;
13117
13684
  let t3GatewayVolume = config.t3GatewayPort !== void 0;
13118
13685
  let extras;
13686
+ let present;
13119
13687
  if (dockerProblem === null) {
13120
13688
  t3GatewayVolume ||= (await volumeOwner(run2, context, `mend_${T3_GATEWAY_VOLUME}`)).state === "present";
13689
+ present = await serverPresent(
13690
+ run2,
13691
+ { directory, dockerContext: context, overlays: composeOverlays(config) },
13692
+ serverVolumes({
13693
+ edgeHost: config.edgeHost ?? null,
13694
+ mirrors: mirrorServices(config.mirrors),
13695
+ t3GatewayVolume
13696
+ }),
13697
+ `ghcr.io/sealant-sh/mend:${config.serverVersion}`
13698
+ );
13121
13699
  const control = await volumeOwner(run2, context, MEND_DOCKER_NAMESPACE.control);
13122
13700
  const owner = read.value.identity === null ? null : serverVolumeOwner(Buffer.from(read.value.identity));
13123
13701
  if (control.state === "present" && owner !== null && control.owner === owner) {
@@ -13144,7 +13722,12 @@ var describeUninstall = async (runtime, scope) => {
13144
13722
  const candidates = [
13145
13723
  ...composed.status === 0 ? composed.stdout.split(/\s+/) : [],
13146
13724
  ...guard.status === 0 ? [guard.stdout.trim()] : [],
13725
+ // By its pin too: a re-run after a partial uninstall no longer has the Mend image,
13726
+ // and so no label to read it from.
13727
+ NETWORK_GUARD_IMAGE,
13147
13728
  DOCKER_SERVICE_IMAGE,
13729
+ // The edge's image stays after `--no-edge`, when the overlay no longer names it.
13730
+ EDGE_IMAGE,
13148
13731
  ...holdings.images
13149
13732
  ].filter((image) => IMAGE_REFERENCE2.test(image) && image !== mendImage);
13150
13733
  const found = await findImages(run2, context, [...new Set(candidates)]);
@@ -13161,6 +13744,7 @@ var describeUninstall = async (runtime, scope) => {
13161
13744
  appUrl: config.appUrl,
13162
13745
  dockerContext: context,
13163
13746
  edgeHost: config.edgeHost ?? null,
13747
+ sshPort: config.sshPort,
13164
13748
  mirrors: mirrorServices(config.mirrors),
13165
13749
  t3GatewayVolume,
13166
13750
  generations: countEntries(path20.join(configDir, "generations")),
@@ -13168,7 +13752,8 @@ var describeUninstall = async (runtime, scope) => {
13168
13752
  dockerProblem,
13169
13753
  holdings,
13170
13754
  leftByEarlier: readLeft(configDir),
13171
- ...extras === void 0 ? {} : { extras }
13755
+ ...extras === void 0 ? {} : { extras },
13756
+ ...present === void 0 ? {} : { present }
13172
13757
  };
13173
13758
  }
13174
13759
  }
@@ -13176,10 +13761,35 @@ var describeUninstall = async (runtime, scope) => {
13176
13761
  if (scope !== "server") {
13177
13762
  const cliConfig = path20.join(runtime.cliHome, "cli.json");
13178
13763
  const sshDirectory = path20.join(runtime.cliHome, "ssh");
13764
+ const installed = isInstallation(server) && server.appUrl !== "" ? server : null;
13765
+ const appHost = installed === null ? null : parseUrl2(installed.appUrl)?.hostname;
13766
+ const owned = sshBlockOwned({
13767
+ urls: [
13768
+ ...runtime.signedIn === null ? [] : [runtime.signedIn.url],
13769
+ ...installed === null ? [] : [installed.appUrl],
13770
+ ...installed?.edgeHost == null ? [] : [`https://${installed.edgeHost}`]
13771
+ ],
13772
+ gateway: installed?.sshPort === void 0 ? null : {
13773
+ hosts: [
13774
+ "localhost",
13775
+ "127.0.0.1",
13776
+ "::1",
13777
+ ...appHost == null ? [] : [appHost.replace(/^\[|\]$/g, "").toLowerCase()],
13778
+ ...installed.edgeHost == null ? [] : [installed.edgeHost.toLowerCase()]
13779
+ ],
13780
+ port: installed.sshPort
13781
+ }
13782
+ });
13783
+ const blocks = readSshBlocks(runtime.sshConfigFile);
13784
+ const kept = blocks.filter((block) => !owned(block));
13785
+ const keyUsers = kept.filter((block) => block.identityFile !== null && within(sshDirectory, block.identityFile)).map((block) => block.alias);
13786
+ const sshDirectoryHere = exists(sshDirectory);
13179
13787
  home = {
13180
13788
  cliConfig: exists(cliConfig) ? cliConfig : null,
13181
- sshDirectory: exists(sshDirectory) ? sshDirectory : null,
13182
- managedSshBlocks: managedBlockCount(runtime.sshConfigFile),
13789
+ sshDirectory: sshDirectoryHere && keyUsers.length === 0 ? sshDirectory : null,
13790
+ sshBlocks: blocks.filter(owned),
13791
+ sshBlocksKept: kept,
13792
+ ...sshDirectoryHere && keyUsers.length > 0 ? { sshDirectoryKept: { directory: sshDirectory, aliases: keyUsers } } : {},
13183
13793
  signedIn: runtime.signedIn,
13184
13794
  signedInToThisServer: runtime.signedIn !== null && isInstallation(server) && server.appUrl !== "" && signedInTo(runtime.signedIn.url, server.appUrl, server.edgeHost)
13185
13795
  };
@@ -13220,17 +13830,17 @@ var planLines = (plan, configDir) => {
13220
13830
  `server Mend ${version}${appUrl === "" ? "" : ` at ${appUrl}`}${dockerContext === "" ? "" : ` \xB7 docker context ${dockerContext}`}`
13221
13831
  );
13222
13832
  if (dockerContext !== "") {
13223
- const mirrors = plan.server.mirrors ?? [];
13224
- const edge = [...edgeHost === null ? [] : ["edge"], ...mirrors];
13225
- const edgeVolumes = [
13226
- ...edgeHost === null ? [] : ["mend-edge-data", "mend-edge-config"],
13227
- ...mirrors.map((service) => `mend-${service}`),
13228
- // The t3code gateway's state, with paired people's device tokens, when it is there.
13229
- ...plan.server.t3GatewayVolume === true ? [T3_GATEWAY_VOLUME] : []
13833
+ const present = plan.server.present;
13834
+ const containers = present?.containers ?? serverServices(plan.server);
13835
+ const volumes = present?.volumes ?? serverVolumes(plan.server);
13836
+ const image = present === void 0 || present.image;
13837
+ const parts = [
13838
+ ...containers.length === 0 ? [] : [`containers ${containers.join(", ")}`],
13839
+ ...volumes.length === 0 ? [] : [`volumes ${volumes.join(", ")}`],
13840
+ ...image ? [`image ghcr.io/sealant-sh/mend:${version}`] : [],
13841
+ ...edgeHost === null ? [] : [`the edge for ${edgeHost}`]
13230
13842
  ];
13231
- lines.push(
13232
- ` containers ${["mend", "postgres", "garage", ...edge].join(", ")} \xB7 volumes ${[MEND_DOCKER_NAMESPACE_WITH_GARAGE.store, ...secondaryVolumesOf(MEND_DOCKER_NAMESPACE_WITH_GARAGE), "mend-config", "mend-ssh", "mend-postgres", ...edgeVolumes].join(", ")} \xB7 image ghcr.io/sealant-sh/mend:${version}${edgeHost === null ? "" : ` \xB7 the edge for ${edgeHost}`}`
13233
- );
13843
+ if (parts.length > 0) lines.push(` ${parts.join(" \xB7 ")}`);
13234
13844
  }
13235
13845
  lines.push(
13236
13846
  ` ${configDir}: identity.env, active, ${plural(generations, "generation")}, ${plural(backups, "backup")}`
@@ -13270,20 +13880,29 @@ var planLines = (plan, configDir) => {
13270
13880
  );
13271
13881
  }
13272
13882
  if (plan.home.sshDirectory !== null) parts.push(plan.home.sshDirectory);
13273
- if (plan.home.managedSshBlocks > 0) {
13274
- parts.push(`${plural(plan.home.managedSshBlocks, "managed block")} in ~/.ssh/config`);
13275
- }
13883
+ for (const block of plan.home.sshBlocks) parts.push(`~/.ssh/config ${blockLabel(block)}`);
13276
13884
  if (plan.home.signedIn !== null && plan.home.signedInToThisServer !== true) {
13277
13885
  parts.push(`this machine's workspace ssh key on ${plan.home.signedIn.url}, if registered`);
13278
13886
  }
13279
13887
  lines.push(parts.length === 0 ? "home nothing of Mend's here" : `home ${parts[0]}`);
13280
13888
  for (const part of parts.slice(1)) lines.push(` ${part}`);
13889
+ for (const block of plan.home.sshBlocksKept ?? []) {
13890
+ lines.push(
13891
+ block.legacy ? `stays ~/.ssh/config ${blockLabel(block)}: an older mend ssh setup wrote it and it names no server` : `stays ~/.ssh/config ${blockLabel(block)}: another server's`
13892
+ );
13893
+ }
13894
+ const keyKept = plan.home.sshDirectoryKept;
13895
+ if (keyKept !== void 0) {
13896
+ lines.push(
13897
+ `stays ${keyKept.directory}: ${keyKept.aliases.map((alias) => `Host ${alias}`).join(", ")} ${keyKept.aliases.length === 1 ? "signs" : "sign"} with a key in it`
13898
+ );
13899
+ }
13281
13900
  }
13282
13901
  return lines;
13283
13902
  };
13284
13903
  var planDeletesData = (plan) => plan.server !== null && plan.server !== "none";
13285
- var planIsEmpty = (plan) => (plan.server === null || plan.server === "none") && (plan.home === null || plan.home.cliConfig === null && plan.home.sshDirectory === null && plan.home.managedSshBlocks === 0);
13286
- var removeWorkspaces = async (run2, context, holdings, report) => {
13904
+ var planIsEmpty = (plan) => (plan.server === null || plan.server === "none") && (plan.home === null || plan.home.cliConfig === null && plan.home.sshDirectory === null && plan.home.sshBlocks.length === 0);
13905
+ var removeWorkspaceContainers = async (run2, context, holdings, report) => {
13287
13906
  const left = [];
13288
13907
  const containers = [
13289
13908
  ...holdings.workspaces.map((workspace) => workspace.name),
@@ -13308,8 +13927,12 @@ var removeWorkspaces = async (run2, context, holdings, report) => {
13308
13927
  `removed ${plural(removed.length, "workspace container")}${live > 0 ? `, ${live} of them live` : ""}, with their volumes (${listOf(removed)})`
13309
13928
  );
13310
13929
  }
13930
+ return left;
13931
+ };
13932
+ var removeWorkspaceNetworks = async (run2, context, names, report) => {
13933
+ const left = [];
13311
13934
  const networks = [];
13312
- for (const name of holdings.networks) {
13935
+ for (const name of names) {
13313
13936
  const gone = await dockerIn(run2, context, ["network", "rm", name]);
13314
13937
  if (gone.status === 0 || notFound(gone)) networks.push(name);
13315
13938
  else {
@@ -13381,6 +14004,7 @@ var removeServer = async (runtime, plan, report) => {
13381
14004
  const control = await volumeOwner(run2, context, namespace.control);
13382
14005
  return control.state === "present" && owner !== null && control.owner === owner;
13383
14006
  };
14007
+ const workspaceNetworks = /* @__PURE__ */ new Set();
13384
14008
  const sweepWorkspaces = async () => {
13385
14009
  if (!await controlIsOurs()) return;
13386
14010
  const found = await findWorkspaces(run2, context, namespace.control);
@@ -13388,19 +14012,22 @@ var removeServer = async (runtime, plan, report) => {
13388
14012
  report.failures.push(`could not list the installation's workspaces: ${found.problem}`);
13389
14013
  return;
13390
14014
  }
13391
- left.push(...await removeWorkspaces(run2, context, found, report));
14015
+ left.push(...await removeWorkspaceContainers(run2, context, found, report));
14016
+ for (const name of found.networks) workspaceNetworks.add(name);
13392
14017
  };
13393
14018
  const target = {
13394
14019
  directory: installation.directory,
13395
14020
  dockerContext: context,
13396
14021
  overlays: composeOverlays(installation.config)
13397
14022
  };
14023
+ const services = await composeServices(run2, target);
13398
14024
  await run2("docker", serverComposeArgs(target, ["stop", "--timeout", "30", "mend"]), {
13399
14025
  timeoutMs: serverProcessDeadlines.stop
13400
14026
  });
13401
14027
  await sweepWorkspaces();
13402
14028
  const pending = await pendingHoldings(run2, context, plan.leftByEarlier ?? []);
13403
- left.push(...await removeWorkspaces(run2, context, pending.holdings, report));
14029
+ left.push(...await removeWorkspaceContainers(run2, context, pending.holdings, report));
14030
+ for (const name of pending.holdings.networks) workspaceNetworks.add(name);
13404
14031
  const down = await run2(
13405
14032
  "docker",
13406
14033
  serverComposeArgs(target, ["down", "--volumes", "--remove-orphans", "--timeout", "30"]),
@@ -13411,10 +14038,17 @@ var removeServer = async (runtime, plan, report) => {
13411
14038
  `Docker did not take the server down (docker compose down: ${detail(down)}). Its volumes and files are kept; run mend uninstall again once Docker answers.`
13412
14039
  );
13413
14040
  }
13414
- server.writeLine(
13415
- `removed containers ${["mend", "postgres", "garage", ...mirrorServices(installation.config.mirrors)].join(", ")} and the Compose-owned volumes`
13416
- );
14041
+ const containers = services ?? serverServices({
14042
+ edgeHost: installation.config.edgeHost,
14043
+ mirrors: mirrorServices(installation.config.mirrors)
14044
+ });
14045
+ if (containers.length > 0) {
14046
+ server.writeLine(
14047
+ `removed containers ${containers.join(", ")} and the Compose-owned volumes`
14048
+ );
14049
+ }
13417
14050
  await sweepWorkspaces();
14051
+ left.push(...await removeWorkspaceNetworks(run2, context, [...workspaceNetworks], report));
13418
14052
  const compose = `label=com.docker.compose.project=${MEND_DOCKER_NAMESPACE.project}`;
13419
14053
  const networks = await listNamesIn(run2, context, "network", [compose]);
13420
14054
  if ("problem" in networks) {
@@ -13520,7 +14154,8 @@ var removeLeftovers = async (runtime, plan, report) => {
13520
14154
  report.failures.push(`could not remove container ${name}: ${detail(gone)}`);
13521
14155
  }
13522
14156
  }
13523
- left.push(...await removeWorkspaces(run2, context, plan.holdings, report));
14157
+ left.push(...await removeWorkspaceContainers(run2, context, plan.holdings, report));
14158
+ left.push(...await removeWorkspaceNetworks(run2, context, plan.holdings.networks, report));
13524
14159
  left.push(...await removeEach(run2, context, "network", plan.networks, report));
13525
14160
  const volumes = [];
13526
14161
  for (const name of plan.volumes) {
@@ -13579,21 +14214,44 @@ var removeHostExtras = async (runtime, context, extras, report) => {
13579
14214
  report.remaining.push(HOST_USER_NAMESPACE_SYSCTL_FILE);
13580
14215
  }
13581
14216
  const removed = [];
13582
- const kept = [];
14217
+ let refused = [];
13583
14218
  for (const image of extras.images) {
13584
14219
  const gone = await dockerIn(run2, context, ["image", "rm", image]);
13585
14220
  if (gone.status === 0 || notFound(gone)) removed.push(image);
13586
- else kept.push(image);
14221
+ else refused.push({ image, why: detail(gone) });
14222
+ }
14223
+ const retried = [];
14224
+ for (const { image } of refused) {
14225
+ const gone = await dockerIn(run2, context, ["image", "rm", image]);
14226
+ if (gone.status === 0 || notFound(gone)) removed.push(image);
14227
+ else retried.push({ image, why: detail(gone) });
13587
14228
  }
14229
+ refused = retried;
13588
14230
  if (removed.length > 0) {
13589
14231
  report.write(`removed ${plural(removed.length, "image")} (${listOf(removed, 4)})`);
13590
14232
  }
13591
- if (kept.length > 0) {
14233
+ for (const { image, why } of refused) {
13592
14234
  report.leftovers.push(
13593
- `${plural(kept.length, "image")} another container still uses: ${kept.join(", ")}`
14235
+ `image ${image}: ${why}. To remove it: docker --context ${context} image rm ${image}`
13594
14236
  );
13595
- report.remaining.push(plural(kept.length, "image"));
13596
14237
  }
14238
+ if (refused.length > 0) report.remaining.push(plural(refused.length, "image"));
14239
+ };
14240
+ var notReachedExtras = (extras) => [
14241
+ ...extras.images.length === 0 ? [] : [`${plural(extras.images.length, "image")} (${listOf(extras.images, 4)})`],
14242
+ ...extras.sysctl.state === "mend" ? [HOST_USER_NAMESPACE_SYSCTL_FILE] : []
14243
+ ];
14244
+ var settleBuildCache = async (runtime, context, size, clear, outcome) => {
14245
+ const prune = `docker --context ${context} builder prune --all removes it`;
14246
+ if (!clear) return { kind: "kept", line: `Docker's build cache, ${size}: ${prune}` };
14247
+ if (outcome.failures.length > 0) {
14248
+ return {
14249
+ kind: "not reached",
14250
+ line: `Docker's build cache, ${size}: the uninstall stopped before it; run mend uninstall again, or ${prune}`
14251
+ };
14252
+ }
14253
+ const problem = await clearBuildCache(runtime, context);
14254
+ return problem === null ? { kind: "removed", line: `removed Docker's build cache (${size})` } : { kind: "kept", line: `Docker's build cache, ${size} (${problem}): ${prune}` };
13597
14255
  };
13598
14256
  var clearBuildCache = async (runtime, context) => {
13599
14257
  const pruned = await dockerIn(
@@ -13615,15 +14273,16 @@ var removeHome = async (runtime, plan, report) => {
13615
14273
  fs20.rmSync(plan.sshDirectory, { recursive: true, force: true });
13616
14274
  server.writeLine(`removed ${plan.sshDirectory}`);
13617
14275
  }
13618
- if (plan.managedSshBlocks > 0) {
14276
+ if (plan.sshBlocks.length > 0) {
14277
+ const planned = new Set(plan.sshBlocks.map((block) => block.alias));
13619
14278
  try {
13620
14279
  const before = fs20.readFileSync(runtime.sshConfigFile, "utf8");
13621
- const stripped = stripManagedWorkspaceSshBlocks(before);
14280
+ const stripped = stripManagedWorkspaceSshBlocks(before, (block) => planned.has(block.alias));
13622
14281
  if (!stripped.ok) throw stripped.error;
13623
- if (stripped.value.removed > 0) {
14282
+ if (stripped.value.removed.length > 0) {
13624
14283
  fs20.writeFileSync(runtime.sshConfigFile, stripped.value.config, { mode: 384 });
13625
14284
  server.writeLine(
13626
- `removed ${plural(stripped.value.removed, "managed block")} from ${runtime.sshConfigFile}`
14285
+ `removed ${stripped.value.removed.map((block) => `Host ${block.alias}`).join(", ")} from ${runtime.sshConfigFile}`
13627
14286
  );
13628
14287
  }
13629
14288
  } catch (cause) {
@@ -13632,6 +14291,17 @@ var removeHome = async (runtime, plan, report) => {
13632
14291
  );
13633
14292
  }
13634
14293
  }
14294
+ for (const block of plan.sshBlocksKept ?? []) {
14295
+ if (!block.legacy) continue;
14296
+ report.leftovers.push(legacyBlockNote(block, runtime.sshConfigFile));
14297
+ report.remaining.push(`Host ${block.alias} in ${runtime.sshConfigFile}`);
14298
+ }
14299
+ const keyKept = plan.sshDirectoryKept;
14300
+ if (keyKept !== void 0) {
14301
+ report.leftovers.push(
14302
+ `${keyKept.directory}: ${keyKept.aliases.map((alias) => `Host ${alias}`).join(", ")} in ${runtime.sshConfigFile} ${keyKept.aliases.length === 1 ? "signs" : "sign"} with a key in it, so it stays`
14303
+ );
14304
+ }
13635
14305
  let remaining = [];
13636
14306
  try {
13637
14307
  remaining = fs20.readdirSync(runtime.cliHome);
@@ -13644,7 +14314,8 @@ var removeHome = async (runtime, plan, report) => {
13644
14314
  return;
13645
14315
  }
13646
14316
  const serverFiles = remaining.filter((name) => SERVER_OWNED.has(name));
13647
- const others = remaining.filter((name) => !SERVER_OWNED.has(name));
14317
+ const keyDirectory = keyKept === void 0 ? null : path20.basename(keyKept.directory);
14318
+ const others = remaining.filter((name) => !SERVER_OWNED.has(name) && name !== keyDirectory);
13648
14319
  if (serverFiles.length > 0 && !report.remaining.includes(runtime.cliHome)) {
13649
14320
  report.leftovers.push(
13650
14321
  `${runtime.cliHome}: ${serverFiles.join(", ")} ${serverFiles.length === 1 ? "is" : "are"} the server's configuration, which mend uninstall --server removes`
@@ -13688,10 +14359,12 @@ var executeUninstall = async (runtime, plan) => {
13688
14359
  leftovers: [],
13689
14360
  remaining: []
13690
14361
  };
14362
+ const notReached = [];
13691
14363
  const done = () => ({
13692
14364
  failures: report.failures,
13693
14365
  leftovers: report.leftovers,
13694
- remaining: report.remaining
14366
+ remaining: report.remaining,
14367
+ ...notReached.length === 0 ? {} : { notReached }
13695
14368
  });
13696
14369
  const refusal = planRefusal(plan);
13697
14370
  if (refusal !== null) {
@@ -13705,6 +14378,8 @@ var executeUninstall = async (runtime, plan) => {
13705
14378
  serverGone = true;
13706
14379
  if (server === "removed" && plan.server.extras !== void 0) {
13707
14380
  await removeHostExtras(runtime, plan.server.dockerContext, plan.server.extras, report);
14381
+ } else if (plan.server.extras !== void 0) {
14382
+ notReached.push(...notReachedExtras(plan.server.extras));
13708
14383
  }
13709
14384
  } else if (isLeftovers(plan.server)) {
13710
14385
  await removeLeftovers(runtime, plan.server, report);
@@ -14107,10 +14782,10 @@ var withSpinner = async (label, work) => {
14107
14782
  const started = Date.now();
14108
14783
  let frame = 0;
14109
14784
  const timer = setInterval(() => {
14110
- const seconds2 = Math.round((Date.now() - started) / 1e3);
14785
+ const seconds = Math.round((Date.now() - started) / 1e3);
14111
14786
  const text = typeof label === "string" ? label : label();
14112
14787
  chrome.write(
14113
- `\r\x1B[2K ${frames[frame % frames.length]} ${redactCredentials(text)} ${dim7(`${seconds2}s`)} `
14788
+ `\r\x1B[2K ${frames[frame % frames.length]} ${redactCredentials(text)} ${dim7(`${seconds}s`)} `
14114
14789
  );
14115
14790
  frame += 1;
14116
14791
  }, 120);
@@ -14202,11 +14877,8 @@ var adopt = async (config, args) => {
14202
14877
  say7(
14203
14878
  `${dim7(" visible to")} ${visibility === "private" ? "only you" : "everyone in the organization"}`
14204
14879
  );
14205
- if (project2.gitAuthMode === "mend-key") {
14206
- say7(`${dim7(" git auth")} mend key ${dim7("(your Mend key signed this clone)")}`);
14207
- } else if (project2.gitAuthMode === "bridge") {
14208
- say7(`${dim7(" git auth")} bridge ${dim7("(signed through the connected `mend keys share`)")}`);
14209
- }
14880
+ const gitAuth = adoptedGitAuth(source, project2.gitAuthMode);
14881
+ if (gitAuth !== null) say7(`${dim7(" git auth")} ${gitAuth.value} ${dim7(`(${gitAuth.note})`)}`);
14210
14882
  say7(
14211
14883
  `${dim7(" sessions start with:")} mend codex ${dim7("(from anywhere \u2014")} --project ${project2.name}${dim7(")")}`
14212
14884
  );
@@ -15680,16 +16352,6 @@ var serviceCommand = async (config, args) => {
15680
16352
  }
15681
16353
  };
15682
16354
  var kilobytes = (bytes) => bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
15683
- var memoryPathOf = (name) => {
15684
- if (name.startsWith(".")) return name;
15685
- const single = AGENT_MEMORY_FILES.find((file) => file.path.endsWith(`/${name}`));
15686
- if (single !== void 0) return single.path;
15687
- const qualified = /^([a-z]+):(.+)$/.exec(name);
15688
- const harness = qualified?.[1] ?? "claude";
15689
- const rest = qualified?.[2] ?? name;
15690
- const root = AGENT_MEMORY_ROOTS.find((candidate) => candidate.harness === harness)?.root;
15691
- return root === void 0 ? name : `${root}/${rest}`;
15692
- };
15693
16355
  var memoryImport = async (config, args) => {
15694
16356
  const repoRoot = cwdFacts(process.cwd()).repoRoot;
15695
16357
  if (repoRoot === null) return fail7("run mend memory import inside the repository's checkout");
@@ -15744,7 +16406,7 @@ var memoryCommand = async (config, args) => {
15744
16406
  (arg, index) => !arg.startsWith("--") && rest[index - 1] !== "--project"
15745
16407
  );
15746
16408
  if (name === void 0) return fail7(usageOf(`memory ${verb}`));
15747
- const query = `?path=${encodeURIComponent(memoryPathOf(name))}`;
16409
+ const query = `?path=${encodeURIComponent(agentMemoryPathOf(name))}`;
15748
16410
  if (verb === "rm") {
15749
16411
  const removed = await api(
15750
16412
  config,
@@ -15850,7 +16512,7 @@ var localCredential = (provider) => {
15850
16512
  )
15851
16513
  );
15852
16514
  case "github": {
15853
- const result = spawnSync6("gh", ["auth", "token"], { encoding: "utf8" });
16515
+ const result = spawnSync7("gh", ["auth", "token"], { encoding: "utf8" });
15854
16516
  const token = result.status === 0 ? result.stdout.trim() : "";
15855
16517
  return token === "" ? null : token;
15856
16518
  }
@@ -16206,7 +16868,10 @@ var uninstallCommand = async (config, args) => {
16206
16868
  ),
16207
16869
  forgetSignIn: () => saveCliConfig({ ...config, token: null, deviceId: null })
16208
16870
  };
16209
- const plan = await describeUninstall(runtime, scope);
16871
+ const plan = await describeUninstall(runtime, scope).catch(
16872
+ (error) => error instanceof ServerStoreError ? error : Promise.reject(error)
16873
+ );
16874
+ if (plan instanceof ServerStoreError) return fail7(plan.message);
16210
16875
  say7(dim7(`mend uninstall \xB7 ${scope === "all" ? "everything" : scope}`));
16211
16876
  for (const line of planLines(plan, server.configDir)) say7(` ${line}`);
16212
16877
  if (planIsEmpty(plan)) {
@@ -16230,19 +16895,24 @@ var uninstallCommand = async (config, args) => {
16230
16895
  const outcome = await executeUninstall(runtime, plan);
16231
16896
  const remaining = [...outcome.remaining];
16232
16897
  const leftovers = [...outcome.leftovers];
16898
+ const notReached = [...outcome.notReached ?? []];
16233
16899
  if (extras?.buildCache != null && plan.server !== null && plan.server !== "none" && !("kind" in plan.server)) {
16234
- const context = plan.server.dockerContext;
16235
- const problem = clearCache && outcome.failures.length === 0 ? await clearBuildCache(runtime, context) : "kept";
16236
- if (problem === null) say7(`removed Docker's build cache (${extras.buildCache})`);
16900
+ const cache = await settleBuildCache(
16901
+ runtime,
16902
+ plan.server.dockerContext,
16903
+ extras.buildCache,
16904
+ clearCache,
16905
+ outcome
16906
+ );
16907
+ if (cache.kind === "removed") say7(cache.line);
16237
16908
  else {
16238
- leftovers.push(
16239
- `Docker's build cache, ${extras.buildCache}${problem === "kept" ? "" : ` (${problem})`}: docker --context ${context} builder prune --all removes it`
16240
- );
16909
+ (cache.kind === "kept" ? leftovers : notReached).push(cache.line);
16241
16910
  remaining.push(`Docker's build cache (${extras.buildCache})`);
16242
16911
  }
16243
16912
  }
16244
16913
  if (scope === "all") remaining.push("the mend CLI itself (npm uninstall -g @sealant/mend)");
16245
16914
  for (const line of leftovers) say7(dim7(` kept \xB7 ${line}`));
16915
+ for (const line of notReached) say7(dim7(` not reached \xB7 ${line}`));
16246
16916
  if (outcome.failures.length > 0) {
16247
16917
  return fail7(outcome.failures.join("\n"));
16248
16918
  }
@@ -16850,17 +17520,22 @@ var restoreTerminal = () => {
16850
17520
  };
16851
17521
  process.once("exit", restoreTerminal);
16852
17522
  var terminalGone = false;
17523
+ var readerGone = false;
16853
17524
  var stopForegroundSession = null;
16854
17525
  var exitOnceStopped = async (stop) => process.exit(await stop() ? 0 : 1);
16855
17526
  var onStreamError = (stream) => (error) => {
17527
+ if (readerGone) return;
16856
17528
  const closedTerminal = stream.isTTY === true && (error.code === "EIO" || error.code === "EPIPE");
16857
17529
  if (!closedTerminal && error.code !== "EPIPE") throw error;
16858
17530
  if (recordedOutput) return;
16859
- if (!closedTerminal) process.exit(0);
17531
+ if (!closedTerminal) {
17532
+ readerGone = true;
17533
+ return whenServerLockReleased(() => process.exit(0));
17534
+ }
16860
17535
  if (terminalGone) return;
16861
17536
  terminalGone = true;
16862
17537
  const stop = stopForegroundSession;
16863
- if (stop === null) process.exit(0);
17538
+ if (stop === null) return whenServerLockReleased(() => process.exit(0));
16864
17539
  void exitOnceStopped(stop);
16865
17540
  };
16866
17541
  process.stdout.on("error", onStreamError(process.stdout));
@@ -17672,14 +18347,14 @@ var dashboard = async (config, options = {}) => {
17672
18347
  `the dashboard needs Node >= 26 (node:ffi) \u2014 this is ${process.version}; every other command still works`
17673
18348
  );
17674
18349
  }
17675
- const rerun = spawnSync6(
18350
+ const rerun = spawnSync7(
17676
18351
  process.execPath,
17677
18352
  ["--experimental-ffi", "--disable-warning=ExperimentalWarning", ...process.argv.slice(1)],
17678
18353
  { stdio: "inherit" }
17679
18354
  );
17680
18355
  process.exit(rerun.status ?? 0);
17681
18356
  }
17682
- const { runDashboard } = await import("./dashboard-JGR77HVG.js");
18357
+ const { runDashboard } = await import("./dashboard-URVZ54OS.js");
17683
18358
  const agentShare = await startShareIfBridge(config);
17684
18359
  const tunnels = options.noTunnel === true || serverIsLocal(config) ? null : createServiceTunnels({
17685
18360
  listServices: () => fetchServices(config),
@@ -17755,7 +18430,7 @@ var manCommand = (words) => {
17755
18430
  const page = doc === null ? renderManIndex(version) : renderManPage(doc, version);
17756
18431
  const file = path21.join(os13.tmpdir(), `mend-man-${process.pid}-${manFileName(doc)}`);
17757
18432
  fs21.writeFileSync(file, page);
17758
- const result = spawnSync6("man", ["-l", file], { stdio: "inherit" });
18433
+ const result = spawnSync7("man", ["-l", file], { stdio: "inherit" });
17759
18434
  fs21.rmSync(file, { force: true });
17760
18435
  if (result.error !== void 0 || result.status !== 0) {
17761
18436
  sayPage(doc === null ? renderIndex() : renderCommand(doc));
@@ -17851,7 +18526,7 @@ var main = async () => {
17851
18526
  if (rest.includes("--bundle")) return doctorBundle(config, rest);
17852
18527
  return doctorCommand(config, localCredential, claudeGrantSecret, async () => {
17853
18528
  try {
17854
- return (await readServerInstallationFacts(nodeServerRuntime().configDir))?.config.appUrl ?? null;
18529
+ return await readLocalServer(nodeServerRuntime().configDir);
17855
18530
  } catch {
17856
18531
  return null;
17857
18532
  }
@@ -17859,7 +18534,13 @@ var main = async () => {
17859
18534
  case "env":
17860
18535
  return envCommand(config, rest);
17861
18536
  case "ssh":
17862
- return sshCommand(rest, boundApi(config), mendCliHome(), config.url);
18537
+ return sshCommand(
18538
+ rest,
18539
+ boundApi(config),
18540
+ mendCliHome(),
18541
+ config.url,
18542
+ (prefix) => resolveLiveSession(config, prefix, "ssh")
18543
+ );
17863
18544
  case "completions":
17864
18545
  return completionsCommand(rest);
17865
18546
  case "__complete":