@sealant/mend 0.36.0-next.761 → 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 (94) hide show
  1. package/dist/{chunk-D4JBBLJV.js → chunk-BXXA4JXE.js} +2 -1
  2. package/dist/{dashboard-4BJL72T6.js → dashboard-URVZ54OS.js} +1 -1
  3. package/dist/main.js +519 -283
  4. package/man/mend-accounts.1 +1 -1
  5. package/man/mend-adopt.1 +1 -1
  6. package/man/mend-attach.1 +1 -1
  7. package/man/mend-codex.1 +1 -1
  8. package/man/mend-completions.1 +1 -1
  9. package/man/mend-connect-pi.1 +1 -1
  10. package/man/mend-connect.1 +1 -1
  11. package/man/mend-continue.1 +1 -1
  12. package/man/mend-doctor.1 +2 -2
  13. package/man/mend-dotfiles-repo.1 +1 -1
  14. package/man/mend-dotfiles-sync.1 +1 -1
  15. package/man/mend-dotfiles.1 +1 -1
  16. package/man/mend-env-cluster.1 +1 -1
  17. package/man/mend-env-load.1 +1 -1
  18. package/man/mend-env-show.1 +1 -1
  19. package/man/mend-folder-create.1 +1 -1
  20. package/man/mend-folder-list.1 +1 -1
  21. package/man/mend-folder-push.1 +1 -1
  22. package/man/mend-folder-rm.1 +1 -1
  23. package/man/mend-git-author.1 +1 -1
  24. package/man/mend-help.1 +1 -1
  25. package/man/mend-invite.1 +1 -1
  26. package/man/mend-keys-init.1 +1 -1
  27. package/man/mend-keys-mode.1 +1 -1
  28. package/man/mend-keys-share.1 +1 -1
  29. package/man/mend-keys-show.1 +1 -1
  30. package/man/mend-land.1 +1 -1
  31. package/man/mend-login.1 +10 -2
  32. package/man/mend-logout.1 +1 -1
  33. package/man/mend-logs.1 +1 -1
  34. package/man/mend-man.1 +1 -1
  35. package/man/mend-members.1 +1 -1
  36. package/man/mend-memory-import.1 +1 -1
  37. package/man/mend-memory-rm.1 +1 -1
  38. package/man/mend-memory-show.1 +1 -1
  39. package/man/mend-memory.1 +1 -1
  40. package/man/mend-models.1 +1 -1
  41. package/man/mend-operator-exposure.1 +1 -1
  42. package/man/mend-operator-gate.1 +1 -1
  43. package/man/mend-operator-grant-owner.1 +1 -1
  44. package/man/mend-operator-org-create.1 +1 -1
  45. package/man/mend-operator-org-invite-owner.1 +1 -1
  46. package/man/mend-operator-org-list.1 +1 -1
  47. package/man/mend-operator-org-rename.1 +1 -1
  48. package/man/mend-operator-reset-link.1 +1 -1
  49. package/man/mend-pair.1 +1 -1
  50. package/man/mend-projects.1 +1 -1
  51. package/man/mend-pull.1 +1 -1
  52. package/man/mend-refresh.1 +1 -1
  53. package/man/mend-rejoin.1 +1 -1
  54. package/man/mend-resume.1 +1 -1
  55. package/man/mend-run.1 +1 -1
  56. package/man/mend-secrets-add.1 +1 -1
  57. package/man/mend-secrets-rm.1 +1 -1
  58. package/man/mend-secrets.1 +1 -1
  59. package/man/mend-server-logs.1 +1 -1
  60. package/man/mend-server-restart.1 +1 -1
  61. package/man/mend-server-setup.1 +3 -3
  62. package/man/mend-server-start.1 +1 -1
  63. package/man/mend-server-status.1 +1 -1
  64. package/man/mend-server-stop.1 +1 -1
  65. package/man/mend-server-upgrade.1 +1 -1
  66. package/man/mend-server.1 +1 -1
  67. package/man/mend-service-add.1 +1 -1
  68. package/man/mend-service-connect.1 +1 -1
  69. package/man/mend-service-init.1 +1 -1
  70. package/man/mend-service-list.1 +1 -1
  71. package/man/mend-service-logs.1 +1 -1
  72. package/man/mend-service-restart.1 +1 -1
  73. package/man/mend-service-run.1 +1 -1
  74. package/man/mend-service-stop.1 +1 -1
  75. package/man/mend-session-share.1 +1 -1
  76. package/man/mend-sessions.1 +1 -1
  77. package/man/mend-shell.1 +1 -1
  78. package/man/mend-skills-push.1 +1 -1
  79. package/man/mend-skills.1 +1 -1
  80. package/man/mend-snake.1 +1 -1
  81. package/man/mend-ssh-keys-remove.1 +1 -1
  82. package/man/mend-ssh-keys.1 +1 -1
  83. package/man/mend-ssh-setup.1 +1 -1
  84. package/man/mend-ssh.1 +1 -1
  85. package/man/mend-stop.1 +1 -1
  86. package/man/mend-ui.1 +1 -1
  87. package/man/mend-uninstall.1 +2 -2
  88. package/man/mend-version.1 +1 -1
  89. package/man/mend-wait.1 +1 -1
  90. package/man/mend-workspace-replace.1 +1 -1
  91. package/man/mend-worktrees-rm.1 +1 -1
  92. package/man/mend-worktrees.1 +1 -1
  93. package/man/mend.1 +1 -1
  94. package/package.json +2 -2
package/dist/main.js CHANGED
@@ -80,15 +80,15 @@ import {
80
80
  workspaceRetirementLine,
81
81
  worktreeJoinLine,
82
82
  worktreeListsPeople
83
- } from "./chunk-D4JBBLJV.js";
83
+ } from "./chunk-BXXA4JXE.js";
84
84
 
85
85
  // src/main.ts
86
- import { spawn as spawn3, spawnSync as spawnSync6 } from "node:child_process";
86
+ import { spawn as spawn3, spawnSync as spawnSync7 } from "node:child_process";
87
87
  import * as crypto from "node:crypto";
88
88
  import * as fs21 from "node:fs";
89
89
  import { createRequire } from "node:module";
90
90
  import * as net6 from "node:net";
91
- import * as os14 from "node:os";
91
+ import * as os13 from "node:os";
92
92
  import * as path21 from "node:path";
93
93
 
94
94
  // src/agent-memory.ts
@@ -164,7 +164,7 @@ var memoryDisplayName = (filePath) => {
164
164
  if (named === null) return filePath;
165
165
  return named.harness === "claude" ? named.name : `${named.harness}:${named.name}`;
166
166
  };
167
- 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`;
168
168
  var ADDED_NAMED = 20;
169
169
  var importReportLines = (report) => {
170
170
  const lines = [];
@@ -2171,15 +2171,18 @@ var COMMANDS = [
2171
2171
  name: "login",
2172
2172
  section: "start",
2173
2173
  summary: "sign this terminal in through the browser",
2174
- synopsis: ["[--url <server>]"],
2174
+ synopsis: ["[--url <server>] [--open | --no-open]"],
2175
2175
  description: [
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."
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."
2177
2178
  ],
2178
2179
  options: [
2179
2180
  {
2180
2181
  flag: "--url <server>",
2181
2182
  text: "the Mend server. Default: MEND_URL, then http://localhost:3105"
2182
- }
2183
+ },
2184
+ { flag: "--open", text: "open the browser here, even over SSH" },
2185
+ { flag: "--no-open", text: "only print the link and the code" }
2183
2186
  ],
2184
2187
  examples: [
2185
2188
  { command: "mend login --url http://10.0.0.216:3105", text: "sign in to a LAN server" }
@@ -2343,7 +2346,7 @@ var COMMANDS = [
2343
2346
  summary: "check this machine's setup, or bundle it for a bug report",
2344
2347
  synopsis: ["", "--bundle [--out <path>] [--tail <n>]"],
2345
2348
  description: [
2346
- "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.",
2347
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.",
2348
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."
2349
2352
  ],
@@ -3307,8 +3310,8 @@ var COMMANDS = [
3307
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.",
3308
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.",
3309
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.",
3310
- "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.",
3311
- "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. 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.",
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.",
3312
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.",
3313
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."
3314
3317
  ],
@@ -3638,7 +3641,7 @@ var COMMANDS = [
3638
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.",
3639
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.",
3640
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.",
3641
- "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.",
3642
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."
3643
3646
  ],
3644
3647
  options: [
@@ -4110,153 +4113,115 @@ var doctorBundleCommand = async (args, deps) => {
4110
4113
  };
4111
4114
 
4112
4115
  // src/doctor.ts
4116
+ import { spawnSync as spawnSync4 } from "node:child_process";
4113
4117
  import * as fs9 from "node:fs";
4114
4118
  import * as path9 from "node:path";
4115
4119
 
4116
4120
  // src/docker-shutdown.ts
4117
4121
  import { spawnSync as spawnSync3 } from "node:child_process";
4118
4122
  import * as fs8 from "node:fs";
4119
- import * as os5 from "node:os";
4120
4123
  import * as path8 from "node:path";
4121
- var DOCKER_CAPTURE_STOP_GRACE_SECONDS = 3600;
4122
- var DOCKERD_DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 15;
4123
- var flagValue = (argv, name) => {
4124
- for (let index = 0; index < argv.length; index += 1) {
4125
- const arg = argv[index] ?? "";
4126
- if (arg.startsWith(`${name}=`)) return arg.slice(name.length + 1);
4127
- if (arg === name) return argv[index + 1] ?? "";
4128
- }
4129
- return null;
4130
- };
4131
- var seconds = (value) => {
4132
- if (typeof value === "number" && Number.isInteger(value) && value >= 0) return value;
4133
- if (typeof value === "string" && /^\d+$/.test(value.trim())) return Number(value.trim());
4134
- return null;
4135
- };
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;
4136
4128
  var daemonKindOf = (info) => {
4137
4129
  if (/docker desktop/i.test(info.operatingSystem)) return "desktop";
4138
4130
  if (/orbstack/i.test(info.operatingSystem)) return "orbstack";
4139
4131
  if (info.securityOptions.some((option) => option.includes("name=rootless"))) return "rootless";
4140
4132
  return "dockerd";
4141
4133
  };
4142
- var defaultConfigPath = (facts, daemon) => {
4143
- switch (daemon) {
4144
- case "desktop":
4145
- return path8.join(facts.home, ".docker", "daemon.json");
4146
- case "orbstack":
4147
- return path8.join(facts.home, ".orbstack", "config", "docker.json");
4148
- case "rootless":
4149
- return path8.join(
4150
- facts.xdgConfigHome ?? path8.join(facts.home, ".config"),
4151
- "docker",
4152
- "daemon.json"
4153
- );
4154
- case "dockerd":
4155
- 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" };
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}` };
4156
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 };
4157
4147
  };
4158
- var readShutdownTimeout = (facts) => {
4148
+ var readDockerStop = (facts, expected = null) => {
4159
4149
  if (facts.info === null) return { kind: "unknown", why: "docker info did not answer" };
4160
- const daemon = daemonKindOf(facts.info);
4161
- const managed = daemon === "desktop" || daemon === "orbstack";
4162
- const argv = managed ? null : facts.dockerdArgv;
4163
- const unresolved = facts.dockerdUnresolved ?? null;
4164
- if (argv === null && !managed && unresolved !== null) return { kind: "unknown", why: unresolved };
4165
- const configPath = (argv === null ? null : flagValue(argv, "--config-file")) ?? defaultConfigPath(facts, daemon);
4166
- if (argv !== null) {
4167
- const flag = flagValue(argv, "--shutdown-timeout");
4168
- if (flag !== null) {
4169
- const value = seconds(flag);
4170
- return value === null ? { kind: "unknown", why: `dockerd --shutdown-timeout ${flag} unreadable` } : {
4171
- kind: "observed",
4172
- seconds: value,
4173
- source: "dockerd --shutdown-timeout",
4174
- daemon,
4175
- configPath,
4176
- fromFlag: true
4177
- };
4178
- }
4179
- }
4180
- const file = facts.readFile(configPath);
4181
- if (file.kind === "unreadable") return { kind: "unknown", why: `${configPath} unreadable` };
4182
- if (file.kind === "read") {
4183
- let parsed;
4184
- try {
4185
- parsed = JSON.parse(file.text);
4186
- } catch {
4187
- return { kind: "unknown", why: `${configPath} is not JSON` };
4188
- }
4189
- const configured = typeof parsed === "object" && parsed !== null && "shutdown-timeout" in parsed ? parsed["shutdown-timeout"] : void 0;
4190
- if (configured !== void 0) {
4191
- const value = seconds(configured);
4192
- return value === null ? { kind: "unknown", why: `shutdown-timeout in ${configPath} unreadable` } : {
4193
- kind: "observed",
4194
- seconds: value,
4195
- source: configPath,
4196
- daemon,
4197
- configPath,
4198
- fromFlag: false
4199
- };
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 };
4200
4160
  }
4201
4161
  }
4202
- if (argv === null && !managed) {
4203
- return {
4204
- kind: "unknown",
4205
- why: `no dockerd process observed here \xB7 not set in ${configPath}`
4206
- };
4207
- }
4208
4162
  return {
4209
4163
  kind: "observed",
4210
- seconds: DOCKERD_DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,
4211
- source: `dockerd default \xB7 not set in ${configPath}`,
4212
- daemon,
4213
- configPath,
4214
- fromFlag: false
4164
+ waitSeconds,
4165
+ longest,
4166
+ limit: stopLimitOf(facts, daemonKindOf(facts.info))
4215
4167
  };
4216
4168
  };
4217
- var restartWords = (daemon) => {
4218
- switch (daemon) {
4219
- case "desktop":
4220
- return "restart Docker Desktop";
4221
- case "orbstack":
4222
- return "restart OrbStack";
4223
- case "rootless":
4224
- return "systemctl --user restart docker";
4225
- case "dockerd":
4226
- return "restart dockerd";
4227
- }
4228
- };
4229
- 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)}`;
4230
- 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) => {
4231
4196
  if (reading.kind === "unknown") {
4232
4197
  return {
4233
4198
  label: "docker",
4234
4199
  state: "todo",
4235
- detail: `shutdown-timeout not observed \xB7 ${reading.why}`,
4200
+ detail: `Docker stop not observed \xB7 ${reading.why}`,
4236
4201
  fix: null
4237
4202
  };
4238
4203
  }
4239
- if (reading.seconds >= grace) {
4204
+ if (reading.kind === "live-restore") {
4240
4205
  return {
4241
4206
  label: "docker",
4242
4207
  state: "ok",
4243
- 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",
4244
4209
  fix: null
4245
4210
  };
4246
4211
  }
4212
+ const ok = !outlasts(reading);
4247
4213
  return {
4248
4214
  label: "docker",
4249
- state: "todo",
4250
- detail: `shutdown-timeout ${reading.seconds} s \xB7 ${reading.source} \xB7 below the ${grace} s capture grace`,
4251
- fix: raiseShutdownTimeoutWords(reading, grace)
4215
+ state: ok ? "ok" : "todo",
4216
+ detail: `${stopWords(reading)} \xB7 ${limitWords(reading.limit, ok)}`,
4217
+ fix: ok ? null : fixWords(reading)
4252
4218
  };
4253
4219
  };
4254
- var dockerShutdownSetupLine = (reading, grace = DOCKER_CAPTURE_STOP_GRACE_SECONDS) => {
4255
- if (reading.kind === "unknown") {
4256
- 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.`;
4257
- }
4258
- if (reading.seconds >= grace) return null;
4259
- 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)}.`;
4260
4225
  };
4261
4226
  var parseDockerInfo = (stdout) => {
4262
4227
  let parsed;
@@ -4271,15 +4236,52 @@ var parseDockerInfo = (stdout) => {
4271
4236
  const options = "SecurityOptions" in parsed ? parsed.SecurityOptions : [];
4272
4237
  return {
4273
4238
  operatingSystem,
4274
- 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
4275
4241
  };
4276
4242
  };
4277
- var readHostFile = (file) => {
4278
- try {
4279
- return { kind: "read", text: fs8.readFileSync(file, "utf8") };
4280
- } catch (cause) {
4281
- 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;
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));
4282
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 };
4283
4285
  };
4284
4286
  var hostProcView = {
4285
4287
  list: (dir) => {
@@ -4416,24 +4418,50 @@ var hostDockerEndpoint = (context = null) => {
4416
4418
  const endpoint = inspected.status === 0 ? inspected.stdout.trim() : "";
4417
4419
  return endpoint === "" ? DOCKER_DEFAULT_HOST : endpoint;
4418
4420
  };
4419
- var dockerdFactsOf = (observation) => {
4420
- switch (observation.kind) {
4421
- case "observed":
4422
- return { dockerdArgv: observation.argv, dockerdUnresolved: null };
4423
- case "none":
4424
- return { dockerdArgv: null, dockerdUnresolved: null };
4425
- case "unresolved":
4426
- return { dockerdArgv: null, dockerdUnresolved: observation.why };
4427
- }
4421
+ var runBounded = (command, args) => {
4422
+ const result = spawnSync3(command, [...args], {
4423
+ encoding: "utf8",
4424
+ timeout: 3e3,
4425
+ stdio: ["ignore", "pipe", "ignore"]
4426
+ });
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
+ };
4428
4463
  };
4429
- var hostDockerDaemonFacts = (infoStdout, context = null) => ({
4430
- info: infoStdout === null ? null : parseDockerInfo(infoStdout),
4431
- ...dockerdFactsOf(observeDockerd(hostProcView, hostDockerEndpoint(context))),
4432
- readFile: readHostFile,
4433
- home: os5.homedir(),
4434
- xdgConfigHome: process.env["XDG_CONFIG_HOME"] ?? null
4435
- });
4436
- var observeHostShutdownTimeout = (context = null) => {
4464
+ var observeHostDockerStop = (context = null) => {
4437
4465
  const info = spawnSync3(
4438
4466
  "docker",
4439
4467
  [...context === null ? [] : ["--context", context], "info", "--format", "{{json .}}"],
@@ -4443,29 +4471,60 @@ var observeHostShutdownTimeout = (context = null) => {
4443
4471
  stdio: ["ignore", "pipe", "ignore"]
4444
4472
  }
4445
4473
  );
4446
- return readShutdownTimeout(
4447
- hostDockerDaemonFacts(info.status === 0 ? info.stdout : null, context)
4448
- );
4474
+ return readDockerStop(hostDockerDaemonFacts(info.status === 0 ? info.stdout : null, context));
4449
4475
  };
4450
4476
 
4451
4477
  // src/doctor.ts
4452
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
+ };
4453
4498
  var MARKS = { ok: "\u2713", todo: "\u25CB", failed: "\u2717" };
4454
4499
  var LABEL_WIDTH = 11;
4455
4500
  var day = (at) => at.toISOString().slice(0, 10);
4456
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}`}`;
4457
4502
  var getJson = async (config, route) => {
4458
4503
  try {
4504
+ const sent = Date.now();
4459
4505
  const response = await fetch(`${config.url}/api${route}`, {
4460
4506
  headers: config.token === null ? {} : { authorization: `Bearer ${config.token}` },
4461
4507
  signal: AbortSignal.timeout(TIMEOUT_MS)
4462
4508
  });
4463
- if (!response.ok) return { value: null, status: response.status };
4464
- 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 };
4465
4513
  } catch {
4466
- return { value: null, status: null };
4514
+ return { value: null, status: null, clockSkewMs: null };
4467
4515
  }
4468
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
+ };
4469
4528
  var exposureCheck = (exposure) => {
4470
4529
  const beyondMachine = exposure.declared !== "loopback" && exposure.originOnMachine !== true;
4471
4530
  const gateOpen = beyondMachine ? exposure.gateOpen : 0;
@@ -4571,6 +4630,8 @@ var runChecks = async (config, probes) => {
4571
4630
  checks.push(
4572
4631
  health.value === null ? await unreachedServer(config, local) : await answeredServer(config, health.value, local)
4573
4632
  );
4633
+ const clock2 = health.value === null || health.clockSkewMs === null ? null : clockCheck(health.clockSkewMs);
4634
+ if (clock2 !== null) checks.push(clock2);
4574
4635
  const projects = health.value !== null && config.token !== null ? await getJson(config, "/projects") : null;
4575
4636
  if (health.value === null) checks.push(notChecked("signed in"));
4576
4637
  else if (config.token === null) {
@@ -4714,9 +4775,12 @@ var runChecks = async (config, probes) => {
4714
4775
  checks.push(exposure === void 0 ? notChecked("exposure") : exposureCheck(exposure));
4715
4776
  const userNamespaces = machine === null || machine.value === null ? void 0 : machine.value.userNamespaces;
4716
4777
  if (userNamespaces !== void 0) checks.push(userNamespacesCheck(userNamespaces));
4717
- if (probes.dockerShutdown !== void 0 && probes.onPath("docker")) {
4718
- checks.push(dockerShutdownCheck(probes.dockerShutdown(local?.dockerContext ?? null)));
4778
+ if (probes.dockerStop !== void 0 && probes.onPath("docker")) {
4779
+ checks.push(dockerStopCheck(probes.dockerStop(local?.dockerContext ?? null)));
4719
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);
4720
4784
  return checks;
4721
4785
  };
4722
4786
  var onPath = (command) => {
@@ -4740,8 +4804,9 @@ var doctorCommand = async (config, localCredential2, claudeGrant2, localServer)
4740
4804
  localCredential: localCredential2,
4741
4805
  claudeGrant: claudeGrant2,
4742
4806
  onPath,
4743
- dockerShutdown: observeHostShutdownTimeout,
4744
- ...localServer === void 0 ? {} : { localServer }
4807
+ dockerStop: observeHostDockerStop,
4808
+ ...localServer === void 0 ? {} : { localServer },
4809
+ ...process.platform === "darwin" ? { macPowerSettings: readMacPowerSettings } : {}
4745
4810
  });
4746
4811
  for (const check of checks) {
4747
4812
  process.stdout.write(`${redactCredentials(formatCheck(check, paintMark))}
@@ -4993,9 +5058,9 @@ var useHttp1 = () => {
4993
5058
  };
4994
5059
 
4995
5060
  // src/landing.ts
4996
- import { spawnSync as spawnSync4 } from "node:child_process";
5061
+ import { spawnSync as spawnSync5 } from "node:child_process";
4997
5062
  import * as fs11 from "node:fs";
4998
- import * as os6 from "node:os";
5063
+ import * as os5 from "node:os";
4999
5064
  import * as path11 from "node:path";
5000
5065
  var paint = (code) => (text) => process.stdout.isTTY === true ? `[${code}m${text}[0m` : text;
5001
5066
  var dim = paint("2");
@@ -5216,7 +5281,7 @@ var landCommand = async (api2, args) => {
5216
5281
  if (!landingSucceeded(report)) process.exitCode = 1;
5217
5282
  };
5218
5283
  var git = (cwd, args) => {
5219
- const result = spawnSync4("git", args, { cwd, encoding: "utf8" });
5284
+ const result = spawnSync5("git", args, { cwd, encoding: "utf8" });
5220
5285
  return {
5221
5286
  status: result.status ?? 1,
5222
5287
  stdout: result.stdout ?? "",
@@ -5292,7 +5357,7 @@ var fetchBundle = (cwd, bundle, into = bundle.branch) => {
5292
5357
  recordAt(previous);
5293
5358
  return { _tag: "unchanged", branch: into, here: previous, tip: bundle.tip };
5294
5359
  }
5295
- const dir = fs11.mkdtempSync(path11.join(os6.tmpdir(), "mend-pull-"));
5360
+ const dir = fs11.mkdtempSync(path11.join(os5.tmpdir(), "mend-pull-"));
5296
5361
  try {
5297
5362
  const file = path11.join(dir, "change.bundle");
5298
5363
  fs11.writeFileSync(file, bundle.bytes, { mode: 384 });
@@ -5534,7 +5599,7 @@ var followStart = async (options) => {
5534
5599
 
5535
5600
  // src/login.ts
5536
5601
  import { spawn as spawn2 } from "node:child_process";
5537
- import * as os7 from "node:os";
5602
+ import * as os6 from "node:os";
5538
5603
 
5539
5604
  // src/pair.ts
5540
5605
  var paint2 = (code) => (text) => process.stdout.isTTY === true ? `\x1B[${code}m${text}\x1B[0m` : text;
@@ -5606,7 +5671,15 @@ var parseCliAuthStart = (json2) => {
5606
5671
  if (typeof deviceCode !== "string" || typeof code !== "string" || typeof verifyPath !== "string" || typeof expiresAt !== "string" || typeof intervalSeconds !== "number") {
5607
5672
  return null;
5608
5673
  }
5609
- 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
+ };
5610
5683
  };
5611
5684
  var parseCliAuthPoll = (json2) => {
5612
5685
  if (typeof json2 !== "object" || json2 === null || !("status" in json2)) return null;
@@ -5665,13 +5738,32 @@ var browserCommand = (platform) => {
5665
5738
  return null;
5666
5739
  };
5667
5740
  var pollDelayMs = (intervalSeconds) => Math.min(Math.max(Math.round(intervalSeconds), 1), 10) * 1e3;
5668
- var pollDeadline = (expiresAt, now = Date.now()) => {
5669
- const at = Date.parse(expiresAt);
5670
- 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 };
5671
5763
  };
5672
5764
  var openBrowser = (url) => {
5673
5765
  const opener = browserCommand(process.platform);
5674
- if (opener === null || process.stdout.isTTY !== true) return;
5766
+ if (opener === null) return;
5675
5767
  try {
5676
5768
  const child = spawn2(opener.command, [...opener.args, url], {
5677
5769
  stdio: "ignore",
@@ -5693,18 +5785,19 @@ var post = async (url, body) => {
5693
5785
  } catch {
5694
5786
  return fail3(`cannot reach the Mend server at ${new URL(url).origin} \u2014 is it running?`);
5695
5787
  }
5788
+ const receivedAt = Date.now();
5696
5789
  const text = await response.text();
5697
5790
  let json2 = null;
5698
5791
  try {
5699
5792
  json2 = JSON.parse(text);
5700
5793
  } catch {
5701
5794
  }
5702
- return { status: response.status, json: json2 };
5795
+ return { status: response.status, json: json2, date: response.headers.get("date"), receivedAt };
5703
5796
  };
5704
5797
  var retryAfterSecondsOf = (json2) => {
5705
5798
  if (typeof json2 === "object" && json2 !== null && "retryAfterSeconds" in json2) {
5706
- const seconds2 = Number(json2.retryAfterSeconds);
5707
- if (Number.isFinite(seconds2) && seconds2 > 0) return seconds2;
5799
+ const seconds = Number(json2.retryAfterSeconds);
5800
+ if (Number.isFinite(seconds) && seconds > 0) return seconds;
5708
5801
  }
5709
5802
  return 5;
5710
5803
  };
@@ -5726,7 +5819,7 @@ var resolveServerUrl = async (args, deps) => {
5726
5819
  };
5727
5820
  var loginCommand = async (args, deps) => {
5728
5821
  const base = await resolveServerUrl(args, deps);
5729
- 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" });
5730
5823
  if (started.status === 429) {
5731
5824
  return fail3(
5732
5825
  `the server asked for a pause \u2014 try again in ${retryAfterSecondsOf(started.json)}s`
@@ -5744,10 +5837,17 @@ var loginCommand = async (args, deps) => {
5744
5837
  ` ${dim3("code")} ${groupCode(opened.code)} ${dim3("\xB7 approve only if the browser shows the same code")}`
5745
5838
  );
5746
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)}`);
5747
5847
  say3("");
5748
5848
  say3(dim3(" waiting for approval\u2026 Ctrl-C stops; nothing is granted until someone approves"));
5749
- openBrowser(url);
5750
- const deadline = pollDeadline(opened.expiresAt);
5849
+ if (browser.open) openBrowser(url);
5850
+ const deadline = pollDeadline(opened, started.receivedAt, started.date);
5751
5851
  const delay2 = pollDelayMs(opened.intervalSeconds);
5752
5852
  while (Date.now() < deadline) {
5753
5853
  await sleep2(delay2);
@@ -6181,9 +6281,9 @@ var operatorCommand = async (api2, tryApi, baseUrl, args) => {
6181
6281
 
6182
6282
  // src/pi-profile.ts
6183
6283
  import * as fs13 from "node:fs";
6184
- import * as os8 from "node:os";
6284
+ import * as os7 from "node:os";
6185
6285
  import * as path13 from "node:path";
6186
- 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");
6187
6287
  var RESOURCE_DIRS = ["extensions", "themes", "prompts"];
6188
6288
  var BESIDE = [
6189
6289
  ["package.json", "package.json"],
@@ -6242,7 +6342,7 @@ var walk = (root, notes) => {
6242
6342
  return found;
6243
6343
  };
6244
6344
  var isLocalSource = (source) => !/^(npm|git):/.test(source) && !/^(https?|ssh|git):\/\//.test(source) && !source.startsWith("git@");
6245
- 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;
6246
6346
  var bundleName = (abs) => {
6247
6347
  try {
6248
6348
  const manifest = JSON.parse(fs13.readFileSync(path13.join(abs, "package.json"), "utf8"));
@@ -6722,10 +6822,10 @@ var parseDuration = (text) => {
6722
6822
  };
6723
6823
  var DURATION_ISSUE = "--timeout takes a duration above 0: 90 or 90s, 5m, 1h";
6724
6824
  var durationLine = (ms) => {
6725
- const seconds2 = Math.round(ms / 1e3);
6726
- if (seconds2 < 60) return `${seconds2} s`;
6727
- const minutes = Math.floor(seconds2 / 60);
6728
- 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;
6729
6829
  if (minutes < 60) return rest === 0 ? `${minutes} min` : `${minutes} min ${rest} s`;
6730
6830
  const hours = Math.floor(minutes / 60);
6731
6831
  return minutes % 60 === 0 ? `${hours} h` : `${hours} h ${minutes % 60} min`;
@@ -6883,7 +6983,7 @@ import * as dns from "node:dns/promises";
6883
6983
  import * as fs16 from "node:fs";
6884
6984
  import { readFile } from "node:fs/promises";
6885
6985
  import * as net4 from "node:net";
6886
- import * as os10 from "node:os";
6986
+ import * as os9 from "node:os";
6887
6987
  import * as path16 from "node:path";
6888
6988
 
6889
6989
  // src/server-docker-volumes.ts
@@ -6892,7 +6992,7 @@ import { createHash as createHash2 } from "node:crypto";
6892
6992
  // src/server-store.ts
6893
6993
  import { randomUUID as randomUUID2 } from "node:crypto";
6894
6994
  import * as fs14 from "node:fs";
6895
- import * as os9 from "node:os";
6995
+ import * as os8 from "node:os";
6896
6996
  import * as path15 from "node:path";
6897
6997
  var ServerRefusal = class extends Error {
6898
6998
  };
@@ -6997,7 +7097,7 @@ var describeOwner = (lockDir) => {
6997
7097
  const owner = parseLockOwner(raw);
6998
7098
  if (owner === null) return "owner metadata is invalid";
6999
7099
  const label = `PID ${owner.pid} on ${owner.hostname}`;
7000
- if (owner.hostname !== os9.hostname()) return label;
7100
+ if (owner.hostname !== os8.hostname()) return label;
7001
7101
  try {
7002
7102
  process.kill(owner.pid, 0);
7003
7103
  return `${label} is still live`;
@@ -7050,7 +7150,7 @@ var acquireLock = (configDir, create) => {
7050
7150
  }
7051
7151
  const owned = fs14.statSync(lockDir);
7052
7152
  const ownerFile = path15.join(lockDir, "owner.json");
7053
- 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() })}
7054
7154
  `;
7055
7155
  let open = true;
7056
7156
  const assertOwned = () => {
@@ -7887,7 +7987,13 @@ var flagsFor = (before, after) => {
7887
7987
  return flags;
7888
7988
  };
7889
7989
  var shellWord = (word) => /^[A-Za-z0-9_./:@=,+-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
7890
- 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(" ");
7891
7997
  var sshAt = (settings) => settings.sshBind ?? settings.bind;
7892
7998
  var sshBeyondThisMachine = (settings) => !isLoopbackAddress(sshAt(settings));
7893
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})`;
@@ -8669,7 +8775,7 @@ var runGuide = async (io, context) => {
8669
8775
  for (const line of changes) io.write(line);
8670
8776
  }
8671
8777
  }
8672
- io.write(`Same as: ${setupCommandOf(flags)}`);
8778
+ io.write(`Same as: ${setupCommandOf(flags, context.given)}`);
8673
8779
  const unresolvedEdge = target.edgeHost !== void 0 && asked.unresolved.has(target.edgeHost) ? target.edgeHost : null;
8674
8780
  if (unresolvedEdge !== null)
8675
8781
  io.write(
@@ -8893,14 +8999,14 @@ var parseSetupOptions = (args) => {
8893
8999
  previous.push(value);
8894
9000
  values.set(flag, previous);
8895
9001
  }
8896
- const flagValue3 = (flag) => values.get(flag)?.[0];
8897
- const version = flagValue3("--version");
8898
- const appPort = flagValue3("--port");
8899
- 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");
8900
9006
  const origins = values.get("--origin");
8901
- const edge = flagValue3("--edge");
8902
- const exposure = flagValue3("--exposure");
8903
- const tenancy = flagValue3("--tenancy");
9007
+ const edge = flagValue2("--edge");
9008
+ const exposure = flagValue2("--exposure");
9009
+ const tenancy = flagValue2("--tenancy");
8904
9010
  const declared = values.get("--declare");
8905
9011
  const declaredItems = declared === void 0 ? void 0 : parseDeclared(declared, "--declare");
8906
9012
  const undeclared = parseDeclared(values.get("--undeclare") ?? [], "--undeclare");
@@ -8919,7 +9025,7 @@ var parseSetupOptions = (args) => {
8919
9025
  };
8920
9026
  const npmMirror = pair("--npm-mirror", "--no-npm-mirror");
8921
9027
  const dockerMirror = pair("--docker-mirror", "--no-docker-mirror");
8922
- const maxSize = flagValue3("--npm-mirror-max-size");
9028
+ const maxSize = flagValue2("--npm-mirror-max-size");
8923
9029
  const npmMirrorMaxSize = maxSize === void 0 ? void 0 : parseMirrorSize(maxSize);
8924
9030
  if (npmMirrorMaxSize === null)
8925
9031
  throw setupError(
@@ -8927,7 +9033,7 @@ var parseSetupOptions = (args) => {
8927
9033
  );
8928
9034
  if (npmMirrorMaxSize !== void 0 && npmMirror === false)
8929
9035
  throw setupError("--npm-mirror-max-size and --no-npm-mirror contradict each other.");
8930
- const dockerMaxSize = flagValue3("--docker-mirror-max-size");
9036
+ const dockerMaxSize = flagValue2("--docker-mirror-max-size");
8931
9037
  const dockerMirrorMaxSize = dockerMaxSize === void 0 ? void 0 : parseMirrorSize(dockerMaxSize);
8932
9038
  if (dockerMirrorMaxSize === null)
8933
9039
  throw setupError(
@@ -8935,7 +9041,7 @@ var parseSetupOptions = (args) => {
8935
9041
  );
8936
9042
  if (dockerMirrorMaxSize !== void 0 && dockerMirror === false)
8937
9043
  throw setupError("--docker-mirror-max-size and --no-docker-mirror contradict each other.");
8938
- const dockerHubUsername = flagValue3("--docker-hub-username");
9044
+ const dockerHubUsername = flagValue2("--docker-hub-username");
8939
9045
  const dockerHubTokenStdin = values.has("--docker-hub-token-stdin");
8940
9046
  const noDockerHubLogin = values.has("--no-docker-hub-login");
8941
9047
  if (dockerHubUsername === void 0 !== !dockerHubTokenStdin)
@@ -8957,22 +9063,22 @@ var parseSetupOptions = (args) => {
8957
9063
  throw setupError(
8958
9064
  `--docker-hub-username and ${noDockerHubLogin ? "--no-docker-hub-login" : "--no-docker-mirror"} contradict each other.`
8959
9065
  );
8960
- const t3GatewayPort = flagValue3("--t3-gateway-port");
9066
+ const t3GatewayPort = flagValue2("--t3-gateway-port");
8961
9067
  if (values.has("--no-t3-gateway") && (values.has("--t3-gateway") || t3GatewayPort !== void 0)) {
8962
9068
  throw setupError("--no-t3-gateway contradicts --t3-gateway and --t3-gateway-port.");
8963
9069
  }
8964
9070
  return {
8965
- context: flagValue3("--context"),
9071
+ context: flagValue2("--context"),
8966
9072
  version: version === void 0 ? void 0 : parseVersion(version),
8967
- bind: flagValue3("--bind"),
8968
- sshBind: flagValue3("--ssh-bind"),
8969
- url: flagValue3("--url"),
9073
+ bind: flagValue2("--bind"),
9074
+ sshBind: flagValue2("--ssh-bind"),
9075
+ url: flagValue2("--url"),
8970
9076
  // `--origin none`: no extra origins at all.
8971
9077
  origins: origins === void 0 ? void 0 : origins[0] === "none" ? [] : origins,
8972
9078
  appPort: appPort === void 0 ? void 0 : parsePort(appPort, "--port"),
8973
9079
  sshPort: sshPort === void 0 ? void 0 : parsePort(sshPort, "--ssh-port"),
8974
- dockerSocket: flagValue3("--docker-socket"),
8975
- assetsDir: flagValue3("--assets-dir"),
9080
+ dockerSocket: flagValue2("--docker-socket"),
9081
+ assetsDir: flagValue2("--assets-dir"),
8976
9082
  offline: values.has("--offline"),
8977
9083
  edge: edge === void 0 ? void 0 : parseEdge(edge),
8978
9084
  noEdge: values.has("--no-edge"),
@@ -9524,7 +9630,8 @@ var checkDocker = async (runtime, context) => {
9524
9630
  }
9525
9631
  return info.stdout.trim();
9526
9632
  };
9527
- 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;
9528
9635
  var observeHostUserNamespaces = async (runtime, context) => {
9529
9636
  const read = HOST_USER_NAMESPACE_FILES.map(
9530
9637
  (file) => `printf '%s|' "$(cat ${file} 2>/dev/null || echo -)"`
@@ -9550,7 +9657,8 @@ var observeHostUserNamespaces = async (runtime, context) => {
9550
9657
  unprivilegedUsernsClone: clone ?? null
9551
9658
  });
9552
9659
  };
9553
- 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)}`;
9554
9662
  var sysctlOf = (setting) => {
9555
9663
  const match = /^([a-z0-9_.]+) = ([0-9]+)$/.exec(setting);
9556
9664
  if (match?.[1] === void 0 || match[2] === void 0) return null;
@@ -9611,10 +9719,10 @@ var settleHostUserNamespaces = async (runtime, options, context) => {
9611
9719
  runtime.writeLine(
9612
9720
  `Sessions cannot start on this host yet: ${who} blocks the unprivileged user namespaces each workspace's Docker service needs.`
9613
9721
  );
9614
- const printFix = (why) => {
9615
- runtime.writeLine(`${why} On the host, run: ${fix}`);
9722
+ const printFix = (why, how = "On the host, run:") => {
9723
+ runtime.writeLine(`${why} ${how} ${fix}`);
9616
9724
  runtime.writeLine("");
9617
- return userNamespacesReminder(observed.setting);
9725
+ return userNamespacesReminder(observed.setting, how);
9618
9726
  };
9619
9727
  if (await rootlessDaemon(runtime, context)) {
9620
9728
  return printFix(
@@ -9627,13 +9735,12 @@ var settleHostUserNamespaces = async (runtime, options, context) => {
9627
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.`
9628
9736
  );
9629
9737
  const answer2 = await runtime.prompter("Allow them now? [Y/n] ");
9630
- if (answer2 === null) throw setupError("Stopped before anything was pulled; nothing changed.");
9738
+ if (answer2 === null) throw setupError("Stopped before setup changed anything.");
9631
9739
  allow = !/^n/i.test(answer2.trim());
9632
9740
  }
9741
+ if (allow === false) return printFix("Left as it is (--no-allow-userns or your answer).");
9633
9742
  if (allow !== true) {
9634
- return printFix(
9635
- 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."
9636
- );
9743
+ return printFix("Setup changes the host's kernel only when asked.", ALLOW_USERNS_RERUN);
9637
9744
  }
9638
9745
  const stopped = await allowHostUserNamespaces(runtime, context, observed.setting);
9639
9746
  if (stopped !== null) return printFix(`Setup could not apply it through Docker (${stopped}).`);
@@ -10514,6 +10621,14 @@ var mirrorsChangedLines = (before, config) => {
10514
10621
  return lines;
10515
10622
  };
10516
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
+ };
10517
10632
  var refuseLegacyContract = (existing) => {
10518
10633
  if (existing !== null && existing.config.assetContract !== ASSET_CONTRACT) {
10519
10634
  throw setupError(
@@ -10547,13 +10662,25 @@ var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10547
10662
  if (read._tag === "error") return { _tag: "error", message: read.error.message };
10548
10663
  const existing = read.value;
10549
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
+ );
10550
10676
  const outcome = await runGuide(
10551
10677
  { write: runtime.writeLine, ask: prompter },
10552
10678
  {
10553
10679
  saved: existing === null ? null : resolveSetupSettings(existing.config, []),
10554
10680
  defaults: resolveSetupSettings(null, []),
10555
10681
  observe: guideObservations(runtime),
10556
- resolve: (flags) => resolveSetupSettings(existing?.config ?? null, flags)
10682
+ resolve: (flags) => resolveSetupSettings(existing?.config ?? null, flags),
10683
+ given: hostFlags2
10557
10684
  }
10558
10685
  );
10559
10686
  if (outcome._tag === "refused") return { _tag: "error", message: outcome.message };
@@ -10564,7 +10691,8 @@ var guidedSetup = async (runtime, prompter, hostFlags2 = []) => {
10564
10691
  return underLock(
10565
10692
  runtime.configDir,
10566
10693
  (store) => setupServer([...outcome.flags, ...hostFlags2], runtime, store, {
10567
- askedAgainst: existing?.directory ?? null
10694
+ askedAgainst: existing?.directory ?? null,
10695
+ userNamespaces: { reminder }
10568
10696
  }),
10569
10697
  { create: true }
10570
10698
  );
@@ -10609,11 +10737,8 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10609
10737
  }
10610
10738
  refuseLegacyContract(existing);
10611
10739
  const variable = runtime.dockerContextVariable;
10612
- const fromVariable = options.context === void 0 && existing === null && variable !== void 0;
10613
- const selectedContext = await selectDockerContext(
10614
- runtime,
10615
- options.context ?? (fromVariable ? variable : existing?.config.dockerContext)
10616
- );
10740
+ const { requested, fromVariable } = requestedDockerContext(runtime, options, existing);
10741
+ const selectedContext = await selectDockerContext(runtime, requested);
10617
10742
  const operatingSystem = await checkDocker(runtime, selectedContext.name);
10618
10743
  runtime.writeLine(
10619
10744
  `Using Docker context "${selectedContext.name}" (${selectedContext.endpoint})${fromVariable ? ", from DOCKER_CONTEXT" : ""}`
@@ -10628,7 +10753,7 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10628
10753
  validateExposure(existing?.config ?? null, options),
10629
10754
  existing?.config ?? null
10630
10755
  );
10631
- const userNamespaces = await settleHostUserNamespaces(runtime, options, selectedContext.name);
10756
+ const userNamespaces = run2.userNamespaces === void 0 ? await settleHostUserNamespaces(runtime, options, selectedContext.name) : run2.userNamespaces.reminder;
10632
10757
  const serverVersion = await resolveServerVersion(runtime, options, existing?.config ?? null);
10633
10758
  const mirrors = resolveMirrors(existing?.config.mirrors, options);
10634
10759
  const configWithoutBucket = {
@@ -10656,9 +10781,10 @@ var setupServer = async (args, runtime, store, run2 = {}) => {
10656
10781
  "--format",
10657
10782
  "{{json .}}"
10658
10783
  ]);
10659
- const line = dockerShutdownSetupLine(
10660
- readShutdownTimeout(
10661
- runtime.dockerDaemonFacts(info.status === 0 ? info.stdout : null, selectedContext.name)
10784
+ const line = dockerStopSetupLine(
10785
+ readDockerStop(
10786
+ runtime.dockerDaemonFacts(info.status === 0 ? info.stdout : null, selectedContext.name),
10787
+ WORKSPACE_STOP_TIMEOUT_SECONDS
10662
10788
  )
10663
10789
  );
10664
10790
  if (line !== null) runtime.writeLine(line);
@@ -10806,7 +10932,7 @@ var reachedBefore = (url, before) => {
10806
10932
  };
10807
10933
  var followUrlChange = async (runtime, options, before, after, instance) => {
10808
10934
  runtime.writeLine(
10809
- `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.`
10810
10936
  );
10811
10937
  const saved = runtime.savedCliLogin?.(runtime.configDir) ?? null;
10812
10938
  if (saved === null || !saved.signedIn || !reachedBefore(saved.url, before) || await answersAs(runtime, saved.url, after.serverVersion, instance)) {
@@ -11549,7 +11675,7 @@ var manageServer = async (command, args, runtime, store) => {
11549
11675
  };
11550
11676
  var nodeServerRuntime = () => {
11551
11677
  const environment = { ...process.env };
11552
- const home = os10.homedir();
11678
+ const home = os9.homedir();
11553
11679
  const configHome = environment["XDG_CONFIG_HOME"] ?? path16.join(home, ".config");
11554
11680
  return {
11555
11681
  configDir: path16.join(configHome, "mend"),
@@ -11590,7 +11716,7 @@ var nodeServerRuntime = () => {
11590
11716
  return null;
11591
11717
  }
11592
11718
  },
11593
- localAddresses: () => reachableAddressesOf(os10.networkInterfaces()),
11719
+ localAddresses: () => reachableAddressesOf(os9.networkInterfaces()),
11594
11720
  readStdin: async () => {
11595
11721
  const chunks = [];
11596
11722
  for await (const chunk of process.stdin)
@@ -11664,7 +11790,7 @@ var portTakenHere = async (port, address = "127.0.0.1") => {
11664
11790
  };
11665
11791
  var probeSshFromHere = async (bind, port) => {
11666
11792
  const unspecified = bind === "0.0.0.0" || bind === "::";
11667
- const addresses = unspecified ? Object.values(os10.networkInterfaces()).flatMap((entries) => entries ?? []).filter(
11793
+ const addresses = unspecified ? Object.values(os9.networkInterfaces()).flatMap((entries) => entries ?? []).filter(
11668
11794
  (entry) => !entry.internal && (entry.family === "IPv4" || bind === "::" && !entry.address.startsWith("fe80"))
11669
11795
  ).map((entry) => entry.address).slice(0, 4) : [bind];
11670
11796
  return Promise.all(
@@ -12247,15 +12373,15 @@ var scanSkillLibrary = (root) => {
12247
12373
 
12248
12374
  // src/ssh-setup.ts
12249
12375
  import * as fs19 from "node:fs";
12250
- import * as os12 from "node:os";
12376
+ import * as os11 from "node:os";
12251
12377
  import * as path19 from "node:path";
12252
12378
 
12253
12379
  // ../../packages/workspace-ssh/src/index.ts
12254
- import { spawnSync as spawnSync5 } from "node:child_process";
12380
+ import { spawnSync as spawnSync6 } from "node:child_process";
12255
12381
  import { createHash as createHash3 } from "node:crypto";
12256
12382
  import * as fs18 from "node:fs";
12257
12383
  import { isIP as isIP3 } from "node:net";
12258
- import * as os11 from "node:os";
12384
+ import * as os10 from "node:os";
12259
12385
  import * as path18 from "node:path";
12260
12386
  var LEGACY_BLOCK_BEGIN = "# >>> mend workspace ssh (managed by `mend ssh setup`) >>>";
12261
12387
  var LEGACY_BLOCK_END = "# <<< mend workspace ssh <<<";
@@ -12344,7 +12470,7 @@ var blockEnd = (alias) => `# <<< mend workspace ssh ${alias} <<<`;
12344
12470
  var hasControls = (value) => /[\p{Cc}\p{Zl}\p{Zp}]/u.test(value);
12345
12471
  var parseIdentityPath = (value) => {
12346
12472
  const resolved = path18.resolve(
12347
- value.startsWith("~/") ? path18.join(os11.homedir(), value.slice(2)) : value
12473
+ value.startsWith("~/") ? path18.join(os10.homedir(), value.slice(2)) : value
12348
12474
  );
12349
12475
  if (value === "" || hasControls(value) || hasControls(resolved) || value.includes("${") || resolved.includes("${")) {
12350
12476
  return failure(
@@ -12543,7 +12669,7 @@ var workspaceSshPublicKeyFingerprint = (publicKey) => {
12543
12669
  var publicKeyIdentity = (publicKey) => publicKey.trim().split(/\s+/).slice(0, 2).join(" ");
12544
12670
  var agentKeys = () => {
12545
12671
  if (!process.env["SSH_AUTH_SOCK"]) return [];
12546
- const listed3 = spawnSync5("ssh-add", ["-L"], {
12672
+ const listed3 = spawnSync6("ssh-add", ["-L"], {
12547
12673
  encoding: "utf8",
12548
12674
  timeout: 3e3,
12549
12675
  stdio: ["ignore", "pipe", "pipe"],
@@ -12571,7 +12697,7 @@ var readRequiredKey = (keyPath, source) => {
12571
12697
  const privatePath = publicPath.slice(0, -".pub".length);
12572
12698
  const read = readText(publicPath);
12573
12699
  if (!read.ok) return read;
12574
- const derived = spawnSync5("ssh-keygen", ["-y", "-P", "", "-f", privatePath], {
12700
+ const derived = spawnSync6("ssh-keygen", ["-y", "-P", "", "-f", privatePath], {
12575
12701
  encoding: "utf8",
12576
12702
  timeout: 3e3,
12577
12703
  stdio: ["ignore", "pipe", "pipe"],
@@ -12631,9 +12757,9 @@ var generateDedicatedKey = (privatePath) => {
12631
12757
  new WorkspaceSshError("key", `Could not create ${path18.dirname(privatePath)}.`, cause)
12632
12758
  );
12633
12759
  }
12634
- const generated = spawnSync5(
12760
+ const generated = spawnSync6(
12635
12761
  "ssh-keygen",
12636
- ["-t", "ed25519", "-f", privatePath, "-N", "", "-C", `mend-${os11.hostname()}`],
12762
+ ["-t", "ed25519", "-f", privatePath, "-N", "", "-C", `mend-${os10.hostname()}`],
12637
12763
  { encoding: "utf8", timeout: 3e3, stdio: ["ignore", "pipe", "pipe"] }
12638
12764
  );
12639
12765
  if (generated.status !== 0) {
@@ -12775,8 +12901,8 @@ var dim5 = ansi("2");
12775
12901
  var green5 = ansi("32");
12776
12902
  var warn = ansi("33");
12777
12903
  var say5 = (line) => console.log(redactCredentials(line));
12778
- var sshConfigPath = () => path19.join(os12.homedir(), ".ssh", "config");
12779
- var flagValue2 = (args, flag) => {
12904
+ var sshConfigPath = () => path19.join(os11.homedir(), ".ssh", "config");
12905
+ var flagValue = (args, flag) => {
12780
12906
  const index = args.indexOf(flag);
12781
12907
  return index === -1 || args[index + 1] === void 0 ? null : String(args[index + 1]);
12782
12908
  };
@@ -12793,7 +12919,7 @@ var showStatus = async (api2, cliHome, serverUrl, args) => {
12793
12919
  const parsedTarget = parseWorkspaceSshTarget({
12794
12920
  serverUrl,
12795
12921
  publishedPort: view.gateway.port,
12796
- hostnameOverride: flagValue2(args, "--host")
12922
+ hostnameOverride: flagValue(args, "--host")
12797
12923
  });
12798
12924
  if (parsedTarget.ok === false) return showFailure(parsedTarget.error.message);
12799
12925
  const config = readWorkspaceSshConfig(sshConfigPath());
@@ -12830,14 +12956,14 @@ var setup = async (api2, cliHome, serverUrl, args) => {
12830
12956
  const parsedTarget = parseWorkspaceSshTarget({
12831
12957
  serverUrl,
12832
12958
  publishedPort: view.gateway.port,
12833
- hostnameOverride: flagValue2(args, "--host")
12959
+ hostnameOverride: flagValue(args, "--host")
12834
12960
  });
12835
12961
  if (parsedTarget.ok === false) return showFailure(parsedTarget.error.message);
12836
12962
  const config = readWorkspaceSshConfig(sshConfigPath());
12837
12963
  if (config.ok === false) return showFailure(config.error.message);
12838
12964
  const picked = pickWorkspaceSshKey({
12839
12965
  configHome: cliHome,
12840
- explicitKeyPath: flagValue2(args, "--key"),
12966
+ explicitKeyPath: flagValue(args, "--key"),
12841
12967
  configuredIdentityFile: configuredWorkspaceSshIdentityFile(config.value, parsedTarget.value),
12842
12968
  create: true
12843
12969
  });
@@ -12845,7 +12971,7 @@ var setup = async (api2, cliHome, serverUrl, args) => {
12845
12971
  if (picked.value === null) return showFailure("No workspace SSH key is available.");
12846
12972
  const registered = await api2("POST", "/workspace-ssh/keys", {
12847
12973
  publicKey: picked.value.publicKey,
12848
- name: os12.hostname()
12974
+ name: os11.hostname()
12849
12975
  });
12850
12976
  const sourceLabel = {
12851
12977
  explicit: "from --key",
@@ -12886,7 +13012,7 @@ var sessionSsh = async (api2, cliHome, serverUrl, session, args) => {
12886
13012
  const parsedTarget = parseWorkspaceSshTarget({
12887
13013
  serverUrl,
12888
13014
  publishedPort: view.gateway.port,
12889
- hostnameOverride: flagValue2(args, "--host")
13015
+ hostnameOverride: flagValue(args, "--host")
12890
13016
  });
12891
13017
  if (parsedTarget.ok === false) return showFailure(parsedTarget.error.message);
12892
13018
  console.log(
@@ -13115,7 +13241,7 @@ var sshCommand = async (args, api2, cliHome, serverUrl, findSession2) => {
13115
13241
 
13116
13242
  // src/uninstall.ts
13117
13243
  import * as fs20 from "node:fs";
13118
- import * as os13 from "node:os";
13244
+ import * as os12 from "node:os";
13119
13245
  import * as path20 from "node:path";
13120
13246
  var UNINSTALL_USAGE = "usage: mend uninstall [--all | --server | --home] [--yes]";
13121
13247
  var parseUninstallArgs = (args) => {
@@ -13200,7 +13326,7 @@ var sshBlockOwned = (owners) => (block) => {
13200
13326
  };
13201
13327
  var blockLabel = (block) => `Host ${block.alias}${block.hostname === null ? "" : ` \u2192 ${block.hostname}${block.port === null ? "" : `:${block.port}`}`}`;
13202
13328
  var within = (directory, file) => {
13203
- const resolved = file.startsWith("~/") ? path20.join(os13.homedir(), file.slice(2)) : file;
13329
+ const resolved = file.startsWith("~/") ? path20.join(os12.homedir(), file.slice(2)) : file;
13204
13330
  const relative6 = path20.relative(directory, resolved);
13205
13331
  return relative6 !== "" && !relative6.startsWith("..") && !path20.isAbsolute(relative6);
13206
13332
  };
@@ -13315,6 +13441,60 @@ var findWorkspaces = async (run2, context, controlVolume) => {
13315
13441
  images: [...images]
13316
13442
  };
13317
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
+ };
13318
13498
  var readLeft = (configDir) => {
13319
13499
  try {
13320
13500
  const parsed = JSON.parse(fs20.readFileSync(path20.join(configDir, LEFT_FILE), "utf8"));
@@ -13503,8 +13683,19 @@ var describeUninstall = async (runtime, scope) => {
13503
13683
  let holdings = NO_HOLDINGS;
13504
13684
  let t3GatewayVolume = config.t3GatewayPort !== void 0;
13505
13685
  let extras;
13686
+ let present;
13506
13687
  if (dockerProblem === null) {
13507
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
+ );
13508
13699
  const control = await volumeOwner(run2, context, MEND_DOCKER_NAMESPACE.control);
13509
13700
  const owner = read.value.identity === null ? null : serverVolumeOwner(Buffer.from(read.value.identity));
13510
13701
  if (control.state === "present" && owner !== null && control.owner === owner) {
@@ -13531,6 +13722,9 @@ var describeUninstall = async (runtime, scope) => {
13531
13722
  const candidates = [
13532
13723
  ...composed.status === 0 ? composed.stdout.split(/\s+/) : [],
13533
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,
13534
13728
  DOCKER_SERVICE_IMAGE,
13535
13729
  // The edge's image stays after `--no-edge`, when the overlay no longer names it.
13536
13730
  EDGE_IMAGE,
@@ -13558,7 +13752,8 @@ var describeUninstall = async (runtime, scope) => {
13558
13752
  dockerProblem,
13559
13753
  holdings,
13560
13754
  leftByEarlier: readLeft(configDir),
13561
- ...extras === void 0 ? {} : { extras }
13755
+ ...extras === void 0 ? {} : { extras },
13756
+ ...present === void 0 ? {} : { present }
13562
13757
  };
13563
13758
  }
13564
13759
  }
@@ -13635,17 +13830,17 @@ var planLines = (plan, configDir) => {
13635
13830
  `server Mend ${version}${appUrl === "" ? "" : ` at ${appUrl}`}${dockerContext === "" ? "" : ` \xB7 docker context ${dockerContext}`}`
13636
13831
  );
13637
13832
  if (dockerContext !== "") {
13638
- const mirrors = plan.server.mirrors ?? [];
13639
- const edge = [...edgeHost === null ? [] : ["edge"], ...mirrors];
13640
- const edgeVolumes = [
13641
- ...edgeHost === null ? [] : ["mend-edge-data", "mend-edge-config"],
13642
- ...mirrors.map((service) => `mend-${service}`),
13643
- // The t3code gateway's state, with paired people's device tokens, when it is there.
13644
- ...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}`]
13645
13842
  ];
13646
- lines.push(
13647
- ` 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}`}`
13648
- );
13843
+ if (parts.length > 0) lines.push(` ${parts.join(" \xB7 ")}`);
13649
13844
  }
13650
13845
  lines.push(
13651
13846
  ` ${configDir}: identity.env, active, ${plural(generations, "generation")}, ${plural(backups, "backup")}`
@@ -13707,7 +13902,7 @@ var planLines = (plan, configDir) => {
13707
13902
  };
13708
13903
  var planDeletesData = (plan) => plan.server !== null && plan.server !== "none";
13709
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);
13710
- var removeWorkspaces = async (run2, context, holdings, report) => {
13905
+ var removeWorkspaceContainers = async (run2, context, holdings, report) => {
13711
13906
  const left = [];
13712
13907
  const containers = [
13713
13908
  ...holdings.workspaces.map((workspace) => workspace.name),
@@ -13732,8 +13927,12 @@ var removeWorkspaces = async (run2, context, holdings, report) => {
13732
13927
  `removed ${plural(removed.length, "workspace container")}${live > 0 ? `, ${live} of them live` : ""}, with their volumes (${listOf(removed)})`
13733
13928
  );
13734
13929
  }
13930
+ return left;
13931
+ };
13932
+ var removeWorkspaceNetworks = async (run2, context, names, report) => {
13933
+ const left = [];
13735
13934
  const networks = [];
13736
- for (const name of holdings.networks) {
13935
+ for (const name of names) {
13737
13936
  const gone = await dockerIn(run2, context, ["network", "rm", name]);
13738
13937
  if (gone.status === 0 || notFound(gone)) networks.push(name);
13739
13938
  else {
@@ -13805,6 +14004,7 @@ var removeServer = async (runtime, plan, report) => {
13805
14004
  const control = await volumeOwner(run2, context, namespace.control);
13806
14005
  return control.state === "present" && owner !== null && control.owner === owner;
13807
14006
  };
14007
+ const workspaceNetworks = /* @__PURE__ */ new Set();
13808
14008
  const sweepWorkspaces = async () => {
13809
14009
  if (!await controlIsOurs()) return;
13810
14010
  const found = await findWorkspaces(run2, context, namespace.control);
@@ -13812,19 +14012,22 @@ var removeServer = async (runtime, plan, report) => {
13812
14012
  report.failures.push(`could not list the installation's workspaces: ${found.problem}`);
13813
14013
  return;
13814
14014
  }
13815
- 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);
13816
14017
  };
13817
14018
  const target = {
13818
14019
  directory: installation.directory,
13819
14020
  dockerContext: context,
13820
14021
  overlays: composeOverlays(installation.config)
13821
14022
  };
14023
+ const services = await composeServices(run2, target);
13822
14024
  await run2("docker", serverComposeArgs(target, ["stop", "--timeout", "30", "mend"]), {
13823
14025
  timeoutMs: serverProcessDeadlines.stop
13824
14026
  });
13825
14027
  await sweepWorkspaces();
13826
14028
  const pending = await pendingHoldings(run2, context, plan.leftByEarlier ?? []);
13827
- 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);
13828
14031
  const down = await run2(
13829
14032
  "docker",
13830
14033
  serverComposeArgs(target, ["down", "--volumes", "--remove-orphans", "--timeout", "30"]),
@@ -13835,10 +14038,17 @@ var removeServer = async (runtime, plan, report) => {
13835
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.`
13836
14039
  );
13837
14040
  }
13838
- server.writeLine(
13839
- `removed containers ${["mend", "postgres", "garage", ...mirrorServices(installation.config.mirrors)].join(", ")} and the Compose-owned volumes`
13840
- );
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
+ }
13841
14050
  await sweepWorkspaces();
14051
+ left.push(...await removeWorkspaceNetworks(run2, context, [...workspaceNetworks], report));
13842
14052
  const compose = `label=com.docker.compose.project=${MEND_DOCKER_NAMESPACE.project}`;
13843
14053
  const networks = await listNamesIn(run2, context, "network", [compose]);
13844
14054
  if ("problem" in networks) {
@@ -13944,7 +14154,8 @@ var removeLeftovers = async (runtime, plan, report) => {
13944
14154
  report.failures.push(`could not remove container ${name}: ${detail(gone)}`);
13945
14155
  }
13946
14156
  }
13947
- 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));
13948
14159
  left.push(...await removeEach(run2, context, "network", plan.networks, report));
13949
14160
  const volumes = [];
13950
14161
  for (const name of plan.volumes) {
@@ -14026,6 +14237,22 @@ var removeHostExtras = async (runtime, context, extras, report) => {
14026
14237
  }
14027
14238
  if (refused.length > 0) report.remaining.push(plural(refused.length, "image"));
14028
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}` };
14255
+ };
14029
14256
  var clearBuildCache = async (runtime, context) => {
14030
14257
  const pruned = await dockerIn(
14031
14258
  runtime.server.run,
@@ -14132,10 +14359,12 @@ var executeUninstall = async (runtime, plan) => {
14132
14359
  leftovers: [],
14133
14360
  remaining: []
14134
14361
  };
14362
+ const notReached = [];
14135
14363
  const done = () => ({
14136
14364
  failures: report.failures,
14137
14365
  leftovers: report.leftovers,
14138
- remaining: report.remaining
14366
+ remaining: report.remaining,
14367
+ ...notReached.length === 0 ? {} : { notReached }
14139
14368
  });
14140
14369
  const refusal = planRefusal(plan);
14141
14370
  if (refusal !== null) {
@@ -14149,6 +14378,8 @@ var executeUninstall = async (runtime, plan) => {
14149
14378
  serverGone = true;
14150
14379
  if (server === "removed" && plan.server.extras !== void 0) {
14151
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));
14152
14383
  }
14153
14384
  } else if (isLeftovers(plan.server)) {
14154
14385
  await removeLeftovers(runtime, plan.server, report);
@@ -14349,10 +14580,10 @@ var worktreesRmCommand = async (deps, argv) => {
14349
14580
  var mendCliHome = () => {
14350
14581
  const xdg = process.env["XDG_CONFIG_HOME"];
14351
14582
  const preferred = path21.join(
14352
- xdg === void 0 || xdg === "" ? path21.join(os14.homedir(), ".config") : xdg,
14583
+ xdg === void 0 || xdg === "" ? path21.join(os13.homedir(), ".config") : xdg,
14353
14584
  "mend"
14354
14585
  );
14355
- const legacy = path21.join(os14.homedir(), ".mend");
14586
+ const legacy = path21.join(os13.homedir(), ".mend");
14356
14587
  return !fs21.existsSync(preferred) && fs21.existsSync(legacy) ? legacy : preferred;
14357
14588
  };
14358
14589
  var CONFIG_PATH = path21.join(mendCliHome(), "cli.json");
@@ -14551,10 +14782,10 @@ var withSpinner = async (label, work) => {
14551
14782
  const started = Date.now();
14552
14783
  let frame = 0;
14553
14784
  const timer = setInterval(() => {
14554
- const seconds2 = Math.round((Date.now() - started) / 1e3);
14785
+ const seconds = Math.round((Date.now() - started) / 1e3);
14555
14786
  const text = typeof label === "string" ? label : label();
14556
14787
  chrome.write(
14557
- `\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`)} `
14558
14789
  );
14559
14790
  frame += 1;
14560
14791
  }, 120);
@@ -16221,7 +16452,7 @@ var secretsCommand = async (config, args) => {
16221
16452
  if (verb === "add" || verb === "rm") {
16222
16453
  const given = rest.find((arg, index) => !arg.startsWith("--") && rest[index - 1] !== "--from");
16223
16454
  if (given === void 0) return fail7(usageOf(`secrets ${verb}`));
16224
- const resolved = secretFilePathOf(given, os14.homedir());
16455
+ const resolved = secretFilePathOf(given, os13.homedir());
16225
16456
  if (resolved.issue !== null) return fail7(resolved.issue);
16226
16457
  if (verb === "rm") {
16227
16458
  const removed = await api(
@@ -16267,7 +16498,7 @@ var secretsCommand = async (config, args) => {
16267
16498
  var isProvider = (value) => value === "claude" || value === "codex" || value === "github";
16268
16499
  var readIfExists = (file) => fs21.existsSync(file) ? fs21.readFileSync(file, "utf8") : null;
16269
16500
  var localCredential = (provider) => {
16270
- const home = os14.homedir();
16501
+ const home = os13.homedir();
16271
16502
  switch (provider) {
16272
16503
  case "codex":
16273
16504
  return readIfExists(
@@ -16281,7 +16512,7 @@ var localCredential = (provider) => {
16281
16512
  )
16282
16513
  );
16283
16514
  case "github": {
16284
- const result = spawnSync6("gh", ["auth", "token"], { encoding: "utf8" });
16515
+ const result = spawnSync7("gh", ["auth", "token"], { encoding: "utf8" });
16285
16516
  const token = result.status === 0 ? result.stdout.trim() : "";
16286
16517
  return token === "" ? null : token;
16287
16518
  }
@@ -16619,7 +16850,7 @@ var uninstallCommand = async (config, args) => {
16619
16850
  const runtime = {
16620
16851
  server,
16621
16852
  cliHome: mendCliHome(),
16622
- sshConfigFile: path21.join(os14.homedir(), ".ssh", "config"),
16853
+ sshConfigFile: path21.join(os13.homedir(), ".ssh", "config"),
16623
16854
  signedIn: config.token === null || !fs21.existsSync(CONFIG_PATH) ? null : { url: config.url, deviceId: config.deviceId },
16624
16855
  revokeDevice: async () => {
16625
16856
  if (config.deviceId === null) return "no device id saved";
@@ -16664,19 +16895,24 @@ var uninstallCommand = async (config, args) => {
16664
16895
  const outcome = await executeUninstall(runtime, plan);
16665
16896
  const remaining = [...outcome.remaining];
16666
16897
  const leftovers = [...outcome.leftovers];
16898
+ const notReached = [...outcome.notReached ?? []];
16667
16899
  if (extras?.buildCache != null && plan.server !== null && plan.server !== "none" && !("kind" in plan.server)) {
16668
- const context = plan.server.dockerContext;
16669
- const problem = clearCache && outcome.failures.length === 0 ? await clearBuildCache(runtime, context) : "kept";
16670
- 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);
16671
16908
  else {
16672
- leftovers.push(
16673
- `Docker's build cache, ${extras.buildCache}${problem === "kept" ? "" : ` (${problem})`}: docker --context ${context} builder prune --all removes it`
16674
- );
16909
+ (cache.kind === "kept" ? leftovers : notReached).push(cache.line);
16675
16910
  remaining.push(`Docker's build cache (${extras.buildCache})`);
16676
16911
  }
16677
16912
  }
16678
16913
  if (scope === "all") remaining.push("the mend CLI itself (npm uninstall -g @sealant/mend)");
16679
16914
  for (const line of leftovers) say7(dim7(` kept \xB7 ${line}`));
16915
+ for (const line of notReached) say7(dim7(` not reached \xB7 ${line}`));
16680
16916
  if (outcome.failures.length > 0) {
16681
16917
  return fail7(outcome.failures.join("\n"));
16682
16918
  }
@@ -16714,7 +16950,7 @@ var keysShare = async (config) => {
16714
16950
  return fail7("SSH_AUTH_SOCK is not set \u2014 start (or plug in) your ssh-agent first");
16715
16951
  }
16716
16952
  await shareAgent({
16717
- url: () => socketUrl(config, "keys-bridge", { host: os14.hostname() }),
16953
+ url: () => socketUrl(config, "keys-bridge", { host: os13.hostname() }),
16718
16954
  agentSock,
16719
16955
  signal: new AbortController().signal,
16720
16956
  onEvent: (event) => {
@@ -16844,7 +17080,7 @@ ${usageOf("dotfiles repo")}`);
16844
17080
  var dotfilesSync = async (config, args) => {
16845
17081
  const all = args.includes("--all");
16846
17082
  const requestedPaths = args.filter((arg) => !arg.startsWith("--"));
16847
- const home = os14.homedir();
17083
+ const home = os13.homedir();
16848
17084
  if (!all && requestedPaths.length === 0) {
16849
17085
  const found = scanDotfileCandidates(home);
16850
17086
  if (found.length === 0) {
@@ -16871,13 +17107,13 @@ var dotfilesSync = async (config, args) => {
16871
17107
  if ("error" in read) return fail7(read.error);
16872
17108
  const result = await api(config, "POST", "/dotfiles/snapshot", {
16873
17109
  files: read.files,
16874
- source: os14.hostname(),
17110
+ source: os13.hostname(),
16875
17111
  merge: false
16876
17112
  });
16877
17113
  const snapshot = result.snapshot;
16878
17114
  if (snapshot === null) return fail7("the server accepted the sync but reports no snapshot");
16879
17115
  say7(
16880
- `${green7("synced")} ${snapshot.files.length} file${snapshot.files.length === 1 ? "" : "s"} from ${os14.hostname()} \xB7 ${dim7(snapshot.sha.slice(0, 7))} ${dim7("\u2014 applies from the next session launch")}`
17116
+ `${green7("synced")} ${snapshot.files.length} file${snapshot.files.length === 1 ? "" : "s"} from ${os13.hostname()} \xB7 ${dim7(snapshot.sha.slice(0, 7))} ${dim7("\u2014 applies from the next session launch")}`
16881
17117
  );
16882
17118
  };
16883
17119
  var envLoad = async (config, args) => {
@@ -17104,7 +17340,7 @@ var skillsList = async (config, args) => {
17104
17340
  };
17105
17341
  var skillsPush = async (config, args) => {
17106
17342
  const dirFlag = takeFlagValue4(args, "--dir");
17107
- const root = dirFlag === null ? path21.join(os14.homedir(), DEFAULT_SKILLS_DIR) : path21.resolve(dirFlag);
17343
+ const root = dirFlag === null ? path21.join(os13.homedir(), DEFAULT_SKILLS_DIR) : path21.resolve(dirFlag);
17108
17344
  const scanned = scanSkillLibrary(root);
17109
17345
  if ("error" in scanned) return fail7(scanned.error);
17110
17346
  for (const note of scanned.notes) say7(dim7(` ${note.skill}: ${note.message}`));
@@ -18111,14 +18347,14 @@ var dashboard = async (config, options = {}) => {
18111
18347
  `the dashboard needs Node >= 26 (node:ffi) \u2014 this is ${process.version}; every other command still works`
18112
18348
  );
18113
18349
  }
18114
- const rerun = spawnSync6(
18350
+ const rerun = spawnSync7(
18115
18351
  process.execPath,
18116
18352
  ["--experimental-ffi", "--disable-warning=ExperimentalWarning", ...process.argv.slice(1)],
18117
18353
  { stdio: "inherit" }
18118
18354
  );
18119
18355
  process.exit(rerun.status ?? 0);
18120
18356
  }
18121
- const { runDashboard } = await import("./dashboard-4BJL72T6.js");
18357
+ const { runDashboard } = await import("./dashboard-URVZ54OS.js");
18122
18358
  const agentShare = await startShareIfBridge(config);
18123
18359
  const tunnels = options.noTunnel === true || serverIsLocal(config) ? null : createServiceTunnels({
18124
18360
  listServices: () => fetchServices(config),
@@ -18152,7 +18388,7 @@ var startShareIfBridge = async (config) => {
18152
18388
  }
18153
18389
  if (access.mode !== "bridge") return null;
18154
18390
  return startAgentShare({
18155
- url: () => socketUrl(config, "keys-bridge", { host: os14.hostname() }),
18391
+ url: () => socketUrl(config, "keys-bridge", { host: os13.hostname() }),
18156
18392
  agentSock
18157
18393
  });
18158
18394
  };
@@ -18192,9 +18428,9 @@ var manCommand = (words) => {
18192
18428
  }
18193
18429
  const version = cliVersion();
18194
18430
  const page = doc === null ? renderManIndex(version) : renderManPage(doc, version);
18195
- const file = path21.join(os14.tmpdir(), `mend-man-${process.pid}-${manFileName(doc)}`);
18431
+ const file = path21.join(os13.tmpdir(), `mend-man-${process.pid}-${manFileName(doc)}`);
18196
18432
  fs21.writeFileSync(file, page);
18197
- const result = spawnSync6("man", ["-l", file], { stdio: "inherit" });
18433
+ const result = spawnSync7("man", ["-l", file], { stdio: "inherit" });
18198
18434
  fs21.rmSync(file, { force: true });
18199
18435
  if (result.error !== void 0 || result.status !== 0) {
18200
18436
  sayPage(doc === null ? renderIndex() : renderCommand(doc));