@dreamtree-org/harness-device 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ - **Dokploy:** secret fields in API responses are redacted before they reach the agent; optional `DOKPLOY_TOOL_PRESET` / `DOKPLOY_ENABLED_TAGS` / `DOKPLOY_DISABLED_TAGS` in config.env limit the tools loaded.
6
+ - **ngrok:** Intel Macs get ngrok's official release in `~/.local/bin`; `ngrok up` waits for every tunnel and lists it; one tunnel can be opened by name (`ngrok up ttyd`); a warning when tunnels share the single URL of a free plan.
7
+ - **Install summary** lists only the MCP servers it registered, and names the ones of yours it kept.
8
+ - `.env` and `.playwright-mcp/` are git-ignored.
9
+
10
+ ## 0.1.1
11
+
12
+ Fixes from the first installs on a real Mac (Intel) and checks on Ubuntu 26.04.
13
+
14
+ - **Sessions came back without their windows on tmux 3.6+** (Ubuntu 26.04, current Homebrew/conda-forge): the layout script used a target that tmux 3.6 rejects for options and stopped before building any window. Fixed on both platforms; the tests' fake tmux now rejects that form too.
15
+ - **Intel Macs:** Homebrew no longer supports them, so setup installs tmux, ttyd and jq from conda-forge through pixi (per user, no sudo).
16
+ - **Docker on macOS:** uses Docker Desktop when it is installed, instead of adding colima next to it.
17
+ - **Your own MCP servers are never replaced:** install skips any user-scope server with the same name that it did not register, and says so.
18
+ - **Updates are safe while services run:** scripts are replaced atomically (overwriting a running bash script crashed it), and on macOS the tmux job keeps its sessions across restarts (`AbandonProcessGroup`).
19
+ - **launchd:** waits for an old job to unload before loading the new one (it failed with "5: Input/output error" and left the service off); heal now also loads jobs that are not loaded at all; the tmux job retries the build every 15 s.
20
+ - **Heal no longer restarts a browser that is still starting** (first minute after a start).
21
+ - **Login Items** names each service (`harness-device-tmux`, `-chromium`, `-ttyd`, `-heal`) instead of four `hd-run` entries.
22
+ - **CLI:** `attach`, `doctor`, `status` and `uninstall` use the device's PATH (they missed tools in `~/.pixi/bin`); `attach` reports launch errors instead of exiting silently; `status` shows the macOS display URL.
23
+
3
24
  ## 0.1.0
4
25
 
5
26
  First release.
package/README.md CHANGED
@@ -89,7 +89,7 @@ Why sessions used to vanish: tmux and everything started inside it are ordinary
89
89
  Needs Node.js 18.17+ and Claude Code (`curl -fsSL https://claude.ai/install.sh | bash`).
90
90
 
91
91
  - **Linux:** Debian or Ubuntu with systemd. System packages come from apt, through one `sudo` prompt.
92
- - **macOS:** [Homebrew](https://brew.sh). Packages are installed as your user, with no sudo.
92
+ - **macOS:** packages are installed as your user, with no sudo. Apple silicon uses [Homebrew](https://brew.sh). Intel Macs, which Homebrew no longer supports, get tmux, ttyd and jq from conda-forge through [pixi](https://pixi.sh), which install downloads into `~/.pixi`. Docker comes from Docker Desktop if it is installed, otherwise colima (Homebrew only).
93
93
 
94
94
  ## Quick Start
95
95
 
@@ -123,6 +123,8 @@ harness-device install
123
123
  harness-device doctor # "Dokploy API accepts the key"
124
124
  ```
125
125
 
126
+ Secrets in Dokploy's API responses (env vars, passwords, tokens) are redacted before they reach the agent (`DOKPLOY_REDACT_ENV=true`). To load fewer Dokploy tools, add any of these to `config.env` and run `install` again: `DOKPLOY_TOOL_PRESET`, `DOKPLOY_ENABLED_TAGS=project,application,postgres`, `DOKPLOY_DISABLED_TAGS`. If you already have your own `dokploy` MCP server, install leaves it as it is and the device's is not registered.
127
+
126
128
  ### Updating
127
129
 
128
130
  Run `install` again with the new version: `npx @dreamtree-org/harness-device@latest install`. It is idempotent. It updates scripts, services, MCP registrations and the skill, and never restarts the tmux session, so live conversations keep running. Add or drop capabilities the same way: `init --with …` / `--without …`, then `install`.
@@ -161,11 +163,11 @@ Pick them with `init --with`/`--without`, or edit `CAPABILITIES=` in `config.env
161
163
  | `browser` | Playwright Chromium | Playwright Chromium | One persistent Chromium on CDP 127.0.0.1:9222 |
162
164
  | `playwright` | | | Playwright MCP attached to that browser; `hd-pw-live` headed runs and UI mode |
163
165
  | `sqlite` | apt `sqlite3` | built in | `sqlite3` |
164
- | `docker` | Docker Engine (`get.docker.com`) | colima + docker CLI | `docker`, `docker compose` |
166
+ | `docker` | Docker Engine (`get.docker.com`) | Docker Desktop, else colima | `docker`, `docker compose` |
165
167
  | `dokploy` | API only | API only | Dokploy MCP against your deployment (`DOKPLOY_URL` + `secrets set DOKPLOY_API_KEY`); nothing is installed |
166
168
  | `graphify` | | | `@dreamtree-org/graphify` CLI; `graphify .` wires a project's graph MCP and hooks |
167
- | `ngrok` | apt repo | Homebrew | Tunnels you open; the agent may only read them |
168
- | `ollama` | ollama.com script | Homebrew | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
169
+ | `ngrok` | apt repo | Homebrew (Intel: ngrok's official release, into `~/.local/bin`) | Tunnels you open; the agent may only read them |
170
+ | `ollama` | ollama.com script | Homebrew (Intel: Ollama app) | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
169
171
 
170
172
  Extra MCP servers for the agent: add `MCP_<name>=command args` lines to `config.env`. They run through `hd-with-secrets`, so API keys stay in `secrets.env`.
171
173
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
5
5
  "author": {
6
6
  "name": "Partha Preetham Krishna",
package/sh/bin/hd-heal CHANGED
@@ -12,8 +12,10 @@ for u in ${HD_UNITS:-}; do
12
12
  hd_svc_restart "$u" || true
13
13
  fi
14
14
  done
15
- # Alive but hung: the CDP endpoint stops answering.
16
- if [[ " ${HD_UNITS:-} " == *" harness-chromium "* ]] && hd_svc_active harness-chromium; then
15
+ # Alive but hung: the CDP endpoint stops answering. A browser that started
16
+ # less than a minute ago may simply not be listening yet: leave it alone.
17
+ if [[ " ${HD_UNITS:-} " == *" harness-chromium "* ]] && hd_svc_active harness-chromium \
18
+ && [ "$(hd_svc_uptime harness-chromium)" -ge 60 ]; then
17
19
  if ! curl -fsS --max-time 5 "http://127.0.0.1:$HD_CDP_PORT/json/version" >/dev/null 2>&1; then
18
20
  hd_log "Chromium is not answering on CDP port $HD_CDP_PORT; restarting"
19
21
  hd_svc_restart harness-chromium || true
package/sh/bin/hd-lib.sh CHANGED
@@ -67,8 +67,31 @@ hd_svc_active() {
67
67
  }
68
68
  hd_svc_restart() {
69
69
  if [ "$HD_OS" = Darwin ]; then
70
- launchctl kickstart -k "gui/$(id -u)/$(hd_svc_label "$1")"
70
+ local l; l="$(hd_svc_label "$1")"
71
+ # Not loaded at all (a failed reload, or turned off and on in Login Items): load it.
72
+ if ! launchctl print "gui/$(id -u)/$l" >/dev/null 2>&1; then
73
+ launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/$l.plist"
74
+ return
75
+ fi
76
+ launchctl kickstart -k "gui/$(id -u)/$l"
71
77
  else
72
78
  systemctl --user restart "$1"
73
79
  fi
74
80
  }
81
+
82
+ # Main process id of a service (empty if not running).
83
+ hd_svc_pid() {
84
+ if [ "$HD_OS" = Darwin ]; then
85
+ launchctl print "gui/$(id -u)/$(hd_svc_label "$1")" 2>/dev/null | awk '/^[[:space:]]*pid = /{print $3; exit}'
86
+ else
87
+ local p; p=$(systemctl --user show -p MainPID --value "$1" 2>/dev/null); [ "${p:-0}" != 0 ] && echo "$p"
88
+ fi
89
+ }
90
+ # Seconds a service has been running (0 if not running).
91
+ hd_svc_uptime() {
92
+ local p; p=$(hd_svc_pid "$1")
93
+ [ -n "$p" ] || { echo 0; return; }
94
+ local t; t=$(ps -o etime= -p "$p" 2>/dev/null | tr -d ' ')
95
+ # etime is [[dd-]hh:]mm:ss
96
+ echo "$t" | awk -F'[-:]' '{s=0; m=1; for(i=NF;i>0;i--){ f=(NF-i==3)?86400:m; s+=$i*f; m*=60 } print s+0}'
97
+ }
@@ -13,8 +13,10 @@ mode="${HD_SERVE_MODE:-conversation}"
13
13
 
14
14
  if ! tmux has-session -t "=$s" 2>/dev/null; then
15
15
  tmux new-session -d -s "$s" -n home -c "$HOME" -x 220 -y 50
16
- tmux set-option -t "=$s" history-limit 50000 >/dev/null
17
- tmux set-option -t "=$s" mouse on >/dev/null
16
+ # Options take a pane target since tmux 3.6: "=name:" (session, its current
17
+ # window) works on every version; a bare "=name" does not on 3.6+.
18
+ tmux set-option -t "=$s:" history-limit 50000 >/dev/null
19
+ tmux set-option -t "=$s:" mouse on >/dev/null
18
20
  hd_log "created tmux session $s"
19
21
  fi
20
22
  for v in DISPLAY HD_HOME HARNESS_DEVICE_HOME CLAUDE_CONFIG_DIR PATH; do [ -n "${!v:-}" ] && tmux set-environment -t "=$s" "$v" "${!v}"; done
@@ -5,7 +5,12 @@
5
5
  # hd-tmux-layout from a oneshot systemd unit instead.)
6
6
  set -u
7
7
  . "$(dirname "$0")/hd-lib.sh"
8
- "$(dirname "$0")/hd-tmux-layout" || hd_log "tmux layout failed"
9
- while tmux has-session -t "=$HD_SESSION" 2>/dev/null; do sleep 15; done
8
+ built=0
9
+ "$(dirname "$0")/hd-tmux-layout" && built=1 || hd_log "tmux layout failed; retrying every 15s"
10
+ while tmux has-session -t "=$HD_SESSION" 2>/dev/null; do
11
+ sleep 15
12
+ # Until a full build succeeds, keep trying: windows must not wait for heal.
13
+ [ "$built" = 1 ] || { "$(dirname "$0")/hd-tmux-layout" && built=1; }
14
+ done
10
15
  hd_log "tmux session $HD_SESSION is gone; exiting so launchd rebuilds it"
11
16
  exit 1
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env bash
2
- # harness-device system setup for macOS (Homebrew). Run by `harness-device
3
- # install` as the user: Homebrew refuses to run as root.
2
+ # harness-device system setup for macOS. Run by `harness-device install` as
3
+ # the user (no sudo). Packages come from Homebrew where it is installed (Apple
4
+ # silicon), else from conda-forge through pixi (Intel Macs, which Homebrew no
5
+ # longer supports), installed per user under ~/.pixi.
4
6
  # darwin.sh --steps base,display,playwright-deps,sqlite,docker,ngrok,ollama
5
7
  # Every step is idempotent: it checks first and skips what is already there.
6
8
  set -euo pipefail
@@ -19,25 +21,45 @@ has() { command -v "$1" >/dev/null 2>&1; }
19
21
  want() { case ",$STEPS," in *",$1,"*) return 0 ;; *) return 1 ;; esac; }
20
22
 
21
23
  [ "$(uname -s)" = Darwin ] || die "this script is for macOS"
22
- [ "$(id -u)" -ne 0 ] || die "run as your user, not root (Homebrew refuses root)"
24
+ [ "$(id -u)" -ne 0 ] || die "run as your user, not root"
23
25
  for b in /opt/homebrew/bin/brew /usr/local/bin/brew; do [ -x "$b" ] && eval "$("$b" shellenv)" && break; done
24
- has brew || die 'Homebrew is required: install it from https://brew.sh (one command), then re-run harness-device install'
26
+ PIXI_HOME="${PIXI_HOME:-$HOME/.pixi}"
27
+ export PATH="$PIXI_HOME/bin:$PATH"
25
28
 
26
- brew_install() {
29
+ ensure_pixi() {
30
+ has pixi && return 0
31
+ log "Homebrew is not available here; installing pixi (conda-forge packages, per user, in $PIXI_HOME)"
32
+ local arch; arch=$(uname -m); [ "$arch" = arm64 ] && arch=aarch64
33
+ local tmp; tmp=$(mktemp -d)
34
+ curl -fsSL -o "$tmp/pixi.tar.gz" "https://github.com/prefix-dev/pixi/releases/latest/download/pixi-$arch-apple-darwin.tar.gz"
35
+ mkdir -p "$PIXI_HOME/bin"
36
+ tar -xzf "$tmp/pixi.tar.gz" -C "$PIXI_HOME/bin" pixi
37
+ chmod 755 "$PIXI_HOME/bin/pixi"
38
+ rm -r "$tmp"
39
+ has pixi || die "pixi did not install"
40
+ }
41
+
42
+ # pkg_install <name>...: whatever is missing, from Homebrew, else conda-forge.
43
+ pkg_install() {
27
44
  local missing=()
28
- for p in "$@"; do brew list --formula "$p" >/dev/null 2>&1 || brew list --cask "$p" >/dev/null 2>&1 || missing+=("$p"); done
45
+ for p in "$@"; do has "$p" || missing+=("$p"); done
29
46
  [ ${#missing[@]} -eq 0 ] && return 0
30
- log "brew install ${missing[*]}"
31
- brew install "${missing[@]}"
47
+ if has brew; then
48
+ log "brew install ${missing[*]}"
49
+ brew install "${missing[@]}"
50
+ else
51
+ ensure_pixi
52
+ for p in "${missing[@]}"; do log "pixi global install $p (conda-forge)"; pixi global install "$p"; done
53
+ fi
32
54
  }
33
55
 
34
56
  if want base; then
35
- brew_install tmux jq git
57
+ pkg_install tmux jq git
36
58
  fi
37
59
 
38
60
  if want display; then
39
61
  # The Mac's own screen is the display; ttyd serves the read-only tmux view.
40
- brew_install ttyd
62
+ pkg_install ttyd
41
63
  log "to watch the screen remotely, turn on System Settings → General → Sharing → Screen Sharing (used over the SSH tunnel)"
42
64
  fi
43
65
 
@@ -46,15 +68,22 @@ if want playwright-deps; then
46
68
  fi
47
69
 
48
70
  if want sqlite; then
49
- has sqlite3 || brew_install sqlite
71
+ has sqlite3 || die "sqlite3 is missing (it ships with macOS): reinstall the Xcode command-line tools"
50
72
  fi
51
73
 
52
74
  if want docker; then
53
- # Docker Engine needs a Linux VM on macOS: colima runs it, without Docker Desktop.
75
+ # Docker Engine needs a Linux VM on macOS: Docker Desktop if installed, else colima.
54
76
  if has docker && docker info >/dev/null 2>&1; then
55
77
  log "docker already works ($(docker --version))"
78
+ elif [ -d /Applications/Docker.app ]; then
79
+ # Docker Desktop is installed: use it, never a second engine next to it.
80
+ log "Docker Desktop is installed but not running; starting it"
81
+ open -g -a Docker || true
82
+ log "for restarts: Docker Desktop → Settings → General → Start Docker Desktop when you sign in"
83
+ elif ! has brew; then
84
+ die "no Docker here: install Docker Desktop (docker.com), or turn the docker capability off"
56
85
  else
57
- brew_install colima docker docker-compose
86
+ brew install colima docker docker-compose
58
87
  mkdir -p "$HOME/.docker/cli-plugins"
59
88
  ln -sfn "$(brew --prefix)/opt/docker-compose/bin/docker-compose" "$HOME/.docker/cli-plugins/docker-compose"
60
89
  # brew services = a LaunchAgent: colima comes back at every login.
@@ -64,12 +93,30 @@ if want docker; then
64
93
  fi
65
94
 
66
95
  if want ngrok; then
67
- has ngrok || brew_install ngrok
96
+ if ! has ngrok; then
97
+ if has brew; then
98
+ brew install ngrok
99
+ else
100
+ # Not on conda-forge: ngrok's own release (its official download host), into ~/.local/bin.
101
+ arch=$(uname -m); [ "$arch" = x86_64 ] && arch=amd64
102
+ log "installing ngrok (official release for darwin-$arch) into ~/.local/bin"
103
+ tmp=$(mktemp -d)
104
+ curl -fsSL -o "$tmp/ngrok.zip" "https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-darwin-$arch.zip"
105
+ mkdir -p "$HOME/.local/bin"
106
+ unzip -o -q "$tmp/ngrok.zip" ngrok -d "$HOME/.local/bin"
107
+ chmod 755 "$HOME/.local/bin/ngrok"
108
+ rm -r "$tmp"
109
+ "$HOME/.local/bin/ngrok" version >/dev/null || die "ngrok did not install"
110
+ fi
111
+ fi
68
112
  fi
69
113
 
70
114
  if want ollama; then
71
- has ollama || brew_install ollama
72
- brew services start ollama >/dev/null 2>&1 || true
115
+ if ! has ollama; then
116
+ has brew || die "install Ollama from https://ollama.com/download (the app starts at login), then re-run install"
117
+ brew install ollama
118
+ brew services start ollama >/dev/null 2>&1 || true
119
+ fi
73
120
  fi
74
121
 
75
122
  log "system steps done: $STEPS"
@@ -15,6 +15,8 @@ import { listSessions, listProcs } from './state.js';
15
15
 
16
16
  export const PLAYWRIGHT_MCP = '@playwright/mcp@0.0.86';
17
17
  export const DOKPLOY_MCP = '@dokploy/mcp@0.30.7';
18
+ /** Optional @dokploy/mcp tool filters, passed through from config.env when set. */
19
+ export const DOKPLOY_OPTIONS = ['DOKPLOY_TOOL_PRESET', 'DOKPLOY_ENABLED_TAGS', 'DOKPLOY_DISABLED_TAGS'];
18
20
 
19
21
  const isMac = (plat) => plat && plat.id === 'darwin';
20
22
 
@@ -53,7 +55,7 @@ export const CAPABILITIES = {
53
55
  const out = [];
54
56
  out.push({ name: 'tmux', ok: !!which('tmux', ctx.env), fix: 'harness-device install' });
55
57
  const s = ctx.cfg.SESSION;
56
- const has = ok('tmux', ['has-session', '-t', `=${s}`]);
58
+ const has = ok('tmux', ['has-session', '-t', `=${s}`], { env: ctx.env });
57
59
  out.push({ name: `tmux session ${s}`, ok: has, fix: 'harness-device restart tmux' });
58
60
  if (has) {
59
61
  for (const x of listSessions(ctx)) {
@@ -146,20 +148,23 @@ One Chromium runs on the display with a persistent profile: logins, cookies and
146
148
  },
147
149
 
148
150
  docker: {
149
- label: 'Docker (Linux: Docker Engine; macOS: colima + docker CLI)',
151
+ label: 'Docker (Linux: Docker Engine; macOS: Docker Desktop if installed, else colima)',
150
152
  system: ['docker'],
151
153
  allow: ['Bash(docker:*)', 'Bash(colima status:*)'],
152
154
  checks: (ctx) => [
153
155
  { name: 'docker CLI', ok: !!which('docker', ctx.env), fix: 'harness-device install' },
154
- { name: 'docker engine reachable', ok: ok('docker', ['info'], { env: ctx.env, timeout: 20000 }), fix: isMac(ctx.platform) ? 'colima start (brew services start colima keeps it on at login)' : 'log out and back in (docker group), then harness-device restart tmux' },
156
+ { name: 'docker engine reachable', ok: ok('docker', ['info'], { env: ctx.env, timeout: 20000 }), fix: isMac(ctx.platform) ? (fs.existsSync('/Applications/Docker.app') ? 'open -a Docker (and turn on Settings → General → Start Docker Desktop when you sign in)' : 'colima start (brew services start colima keeps it on at login)') : 'log out and back in (docker group), then harness-device restart tmux' },
155
157
  ],
156
158
  docs: (cfg, plat) => `## Docker
157
- You can use \`docker\` and \`docker compose\` directly${isMac(plat) ? ' (the engine is colima; `colima status` if docker cannot connect)' : ''}. Name containers after the project, use \`--restart unless-stopped\` for ones that must survive reboots, and remove ones you no longer need. Summary: \`docker_summary\` MCP tool.`,
159
+ You can use \`docker\` and \`docker compose\` directly${isMac(plat) ? ' (the engine is Docker Desktop or colima; if docker cannot connect, tell the user it is not running)' : ''}. Name containers after the project, use \`--restart unless-stopped\` for ones that must survive reboots, and remove ones you no longer need. Summary: \`docker_summary\` MCP tool.`,
158
160
  },
159
161
 
160
162
  dokploy: {
161
163
  label: 'Dokploy (your existing deployment, through its API and the Dokploy MCP)',
162
- mcp: (cfg, p) => [{ name: 'dokploy', command: path.join(p.bin, 'hd-with-secrets'), args: ['env', `DOKPLOY_URL=${cfg.DOKPLOY_URL}`, 'npx', '-y', DOKPLOY_MCP] }],
164
+ // Secrets in API responses (env vars, passwords, tokens) are redacted before
165
+ // they reach the agent; optional tool filters come from config.env.
166
+ mcp: (cfg, p) => [{ name: 'dokploy', command: path.join(p.bin, 'hd-with-secrets'), args: ['env', `DOKPLOY_URL=${cfg.DOKPLOY_URL}`, 'DOKPLOY_REDACT_ENV=true',
167
+ ...DOKPLOY_OPTIONS.filter((k) => cfg[k]).map((k) => `${k}=${cfg[k]}`), 'npx', '-y', DOKPLOY_MCP] }],
163
168
  secrets: ['DOKPLOY_API_KEY'],
164
169
  checks: async (ctx) => {
165
170
  const url = ctx.cfg.DOKPLOY_URL;
package/src/cli.js CHANGED
@@ -101,7 +101,7 @@ function readSecret(prompt) {
101
101
  /** The tmux window this command runs in, if any (to stop an agent killing its own session). */
102
102
  function ownWindow() {
103
103
  if (!process.env.TMUX_PANE) return null;
104
- return capture('tmux', ['display-message', '-p', '-t', process.env.TMUX_PANE, '#{window_name}']) || null;
104
+ return capture('tmux', ['display-message', '-p', '-t', process.env.TMUX_PANE, '#{window_name}'], { env: loadContext(process.env).env }) || null;
105
105
  }
106
106
 
107
107
  function guardOwn(ctx, win, f) {
@@ -137,7 +137,7 @@ function printStatus(s) {
137
137
  console.log(color.bold('\nservices'));
138
138
  console.log(' ' + s.services.map((x) => `${x.state === 'active' ? color.green('●') : color.red('○')} ${x.unit.replace(/^harness-/, '')}`).join(' '));
139
139
  console.log(color.bold('\nviewers') + color.dim(' (127.0.0.1; harness-device tunnel)'));
140
- console.log(` display ${s.viewers.novnc}\n tmux ${s.viewers.tmux}`);
140
+ console.log(` display ${s.viewers.display}\n tmux ${s.viewers.tmux}`);
141
141
  console.log(`\n${color.dim(s.load)}`);
142
142
  if (s.browser) console.log(color.dim(`browser: ${s.browser}`));
143
143
  }
@@ -272,7 +272,8 @@ export async function main(argv) {
272
272
  const ctx = loadContext(env);
273
273
  const target = sub ? (sub.startsWith('rc-') || sub.startsWith('proc-') ? sub : `rc-${sub}`) : null;
274
274
  const t = `=${ctx.cfg.SESSION}${target ? `:${target}` : ''}`;
275
- const r = spawnSync('tmux', process.env.TMUX ? ['switch-client', '-t', t] : ['attach', '-t', t], { stdio: 'inherit' });
275
+ const r = spawnSync('tmux', process.env.TMUX ? ['switch-client', '-t', t] : ['attach', '-t', t], { stdio: 'inherit', env: ctx.env });
276
+ if (r.error) throw new Error(`could not run tmux (${r.error.code}); run: harness-device doctor`);
276
277
  process.exitCode = r.status ?? 1;
277
278
  return;
278
279
  }
@@ -332,9 +333,17 @@ export async function main(argv) {
332
333
  writeFile(p.ngrokYml, ngrok.renderNgrokYml(ctx.cfg, fs.readFileSync(p.ngrokToken, 'utf8').trim(), ctx.platform.id), { mode: 0o600 });
333
334
  writeFile(p.ngrokEnv, ngrok.renderNgrokEnv(names), { mode: 0o600 });
334
335
  ctx.platform.ngrokUp(ctx);
335
- await new Promise((r) => setTimeout(r, 4000));
336
- const s = await device.ngrokStatus();
336
+ // The agent needs a few seconds to connect; wait for every tunnel (up to 30 s).
337
+ let s = { running: false, tunnels: [] };
338
+ for (let i = 0; i < 30; i++) {
339
+ await new Promise((r) => setTimeout(r, 1000));
340
+ s = await device.ngrokStatus();
341
+ if (s.tunnels.length >= names.length) break;
342
+ }
337
343
  for (const t of s.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
344
+ const shared = ngrok.sharedUrls(s.tunnels);
345
+ if (shared.length) log.warn(`Your ngrok plan gives one URL, so ${shared.join(', ')} share it and each request goes to either at random. Open one at a time (e.g. harness-device ngrok up ttyd), or reserve more domains.`);
346
+ if (s.running && s.tunnels.length < names.length) log.warn(`only ${s.tunnels.length} of ${names.length} tunnels are up yet; check: harness-device ngrok status, harness-device logs ngrok`);
338
347
  if (names.some((n) => ['novnc', 'ttyd', 'pwui'].includes(n))) log.info(color.dim(` viewer login: ${ctx.cfg.NGROK_VIEWER_USER} / (NGROK_VIEWER_PASS in ${p.config})`));
339
348
  return log.ok(s.running ? `ngrok up (survives reboots until: harness-device ngrok down)` : 'ngrok did not start yet; check: harness-device logs ngrok');
340
349
  }
@@ -344,7 +353,10 @@ export async function main(argv) {
344
353
  }
345
354
  const s = await device.ngrokStatus();
346
355
  if (!s.running) return console.log('ngrok is not running (harness-device ngrok up <group>)');
356
+ if (!s.tunnels.length) console.log('ngrok is running but no tunnel is up yet (harness-device logs ngrok)');
347
357
  for (const t of s.tunnels) console.log(`${t.name}\t${t.url}\t${t.addr}`);
358
+ const shared = ngrok.sharedUrls(s.tunnels);
359
+ if (shared.length) log.warn(`${shared.join(', ')} share one URL; requests go to either at random`);
348
360
  return;
349
361
  }
350
362
 
package/src/config.js CHANGED
@@ -170,6 +170,9 @@ export function validateConfig(cfg, env = process.env) {
170
170
  if (!['conversation', 'server'].includes(cfg.SERVE_MODE)) errs.push('SERVE_MODE must be conversation or server.');
171
171
  if (!/^\d+$/.test(String(cfg.TRANSCRIPT_DAYS)) || Number(cfg.TRANSCRIPT_DAYS) < 30) errs.push('TRANSCRIPT_DAYS must be a number of days, at least 30.');
172
172
  if (cfg.DOKPLOY_URL && !/^https?:\/\/[^\s'"]+$/.test(cfg.DOKPLOY_URL)) errs.push('DOKPLOY_URL must be an http(s) URL.');
173
+ for (const k of ['DOKPLOY_TOOL_PRESET', 'DOKPLOY_ENABLED_TAGS', 'DOKPLOY_DISABLED_TAGS']) {
174
+ if (cfg[k] && !/^[A-Za-z0-9_,-]+$/.test(cfg[k])) errs.push(`${k} must be a comma-separated list of names (e.g. project,application,postgres).`);
175
+ }
173
176
  for (const k of ['DISPLAY_NUM', 'CDP_PORT', 'VNC_PORT', 'NOVNC_PORT', 'TTYD_PORT', 'PW_UI_PORT']) {
174
177
  if (!/^\d+$/.test(String(cfg[k]))) errs.push(`${k} must be a number (got "${cfg[k]}").`);
175
178
  }
@@ -221,7 +224,7 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
221
224
  // Services start with a bare PATH; keep the one the installer ran with, so
222
225
  // `claude`, `node`, `npx`, nvm/volta and Homebrew installs resolve the same way.
223
226
  PATH: [...new Set([p.bin, path.join(p.pkg, 'node_modules', '.bin'), path.join(env.HOME || os.homedir(), '.local', 'bin'),
224
- ...(platformId === 'darwin' ? ['/opt/homebrew/bin', '/usr/local/bin'] : []),
227
+ ...(platformId === 'darwin' ? [path.join(env.HOME || os.homedir(), '.pixi', 'bin'), '/opt/homebrew/bin', '/usr/local/bin'] : []),
225
228
  ...String(env.PATH || '/usr/local/bin:/usr/bin:/bin').split(':')])].filter(Boolean).join(':'),
226
229
  TERM: 'xterm-256color',
227
230
  LANG: env.LANG || 'C.UTF-8',
package/src/context.js CHANGED
@@ -20,10 +20,22 @@ export function readSecrets(file) {
20
20
  }
21
21
  }
22
22
 
23
+ /**
24
+ * Add the services' PATH (runtime.env) to the caller's, so the CLI finds the
25
+ * same tmux/ttyd the services use (e.g. ~/.pixi/bin) from any shell.
26
+ */
27
+ function withServicePath(env) {
28
+ const f = paths(env).runtimeEnv;
29
+ if (!fs.existsSync(f)) return env;
30
+ const svc = parseEnv(fs.readFileSync(f, 'utf8')).PATH || '';
31
+ const all = [...String(env.PATH || '').split(':'), ...svc.split(':')].filter(Boolean);
32
+ return { ...env, PATH: [...new Set(all)].join(':') };
33
+ }
34
+
23
35
  /** Everything a command needs to know about this device. */
24
36
  export function loadContext(rawEnv = process.env, { dryRun = false } = {}) {
25
37
  const plat = detectPlatform(rawEnv);
26
- const env = plat.userEnv(rawEnv);
38
+ const env = withServicePath(plat.userEnv(rawEnv));
27
39
  const { cfg, exists } = loadConfig(env);
28
40
  const caps = resolveCapabilities(capabilityIds(cfg));
29
41
  return {
package/src/device.js CHANGED
@@ -32,9 +32,9 @@ export function diskUsage(ctx) {
32
32
 
33
33
  export function dockerSummary(ctx) {
34
34
  if (!which('docker', ctx && ctx.env)) return { installed: false };
35
- const ps = capture('docker', ['ps', '-a', '--format', '{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}']);
36
- const df = capture('docker', ['system', 'df']);
37
- return { installed: true, reachable: ok('docker', ['info'], { timeout: 20000 }), containers: ps, df };
35
+ const ps = capture('docker', ['ps', '-a', '--format', '{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'], { env: ctx.env });
36
+ const df = capture('docker', ['system', 'df'], { env: ctx.env });
37
+ return { installed: true, reachable: ok('docker', ['info'], { timeout: 20000, env: ctx.env }), containers: ps, df };
38
38
  }
39
39
 
40
40
  export async function status(ctx) {
package/src/install.js CHANGED
@@ -36,14 +36,19 @@ export async function install(ctx, opts = {}) {
36
36
  const shBin = path.join(PKG_ROOT, 'sh', 'bin');
37
37
  for (const f of fs.readdirSync(shBin)) {
38
38
  if (dryRun) { console.log(color.dim(` copy ${f} → ${p.bin}/`)); continue; }
39
- fs.copyFileSync(path.join(shBin, f), path.join(p.bin, f));
40
- fs.chmodSync(path.join(p.bin, f), f.endsWith('.sh') ? 0o644 : 0o755);
39
+ // Copy, then rename over the old file: a running bash script keeps reading
40
+ // its old copy instead of new bytes at the same offset (which crashes it).
41
+ const dest = path.join(p.bin, f);
42
+ const tmp = `${dest}.new-${process.pid}`;
43
+ fs.copyFileSync(path.join(shBin, f), tmp);
44
+ fs.chmodSync(tmp, f.endsWith('.sh') ? 0o644 : 0o755);
45
+ fs.renameSync(tmp, dest);
41
46
  }
42
47
  writeFile(p.runtimeEnv, renderRuntimeEnv(ctx.cfg, env, { units: ctx.units, platformId: plat.id }), { mode: 0o600, dryRun });
43
48
  writeFile(p.projects, renderProjectsTsv(ctx.cfg), { mode: 0o600, dryRun });
44
49
  if (!fs.existsSync(p.secrets)) writeFile(p.secrets, '# KEY=value, loaded for MCP servers and other tools. Never Anthropic keys.\n', { mode: 0o600, dryRun });
45
50
 
46
- // 2. System packages (Linux: apt through sudo; macOS: Homebrew as the user).
51
+ // 2. System packages (Linux: apt through sudo; macOS: Homebrew or pixi, as the user).
47
52
  if (!opts.skipSystem) plat.systemSetup(ctx, systemStepsFor(ctx.caps), { dryRun });
48
53
 
49
54
  // 3. A persistent copy of this CLI (for the services, the MCP server and the agent) + user-level tools.
@@ -62,7 +67,7 @@ export async function install(ctx, opts = {}) {
62
67
  log.step(`Wiring capabilities into ${ctx.provider.label}`);
63
68
  const servers = allMcpServers(ctx);
64
69
  const res = ctx.provider.apply({ ...ctx, mcpServers: servers, warn: log.warn });
65
- log.info(color.dim(` MCP: ${servers.map((s) => s.name).join(', ')} · pre-approved rules: ${res.allow.length} · denied: ${res.deny.length}`));
70
+ log.info(color.dim(` MCP: ${(res.registered || servers.map((s) => s.name)).join(', ')}${res.skipped && res.skipped.length ? ` (yours kept: ${res.skipped.join(', ')})` : ''} · pre-approved rules: ${res.allow.length} · denied: ${res.deny.length}`));
66
71
 
67
72
  for (const c of ctx.caps) for (const k of c.secrets || []) if (!ctx.secrets[k]) log.warn(`${c.id}: set ${k} with: harness-device secrets set ${k}`);
68
73
  if (ctx.caps.some((c) => c.id === 'dokploy') && !ctx.cfg.DOKPLOY_URL) log.warn('dokploy: set your Dokploy URL with: harness-device init --dokploy-url https://…');
@@ -87,5 +92,5 @@ export function uninstall(ctx, { purge = false } = {}) {
87
92
  if (!dryRun) fs.rmSync(path.join(env.HOME || os.homedir(), '.local', 'bin', 'harness-device'), { force: true });
88
93
  if (purge && !dryRun) fs.rmSync(p.home, { recursive: true, force: true });
89
94
  log.ok(purge ? `Removed services, agent wiring and ${p.home}.` : `Removed services and agent wiring. Config, session state, browser profile and logs stay in ${p.home} (--purge deletes them).`);
90
- log.info(color.dim('System packages (Docker, ngrok, Ollama, apt/Homebrew packages) are left installed.'));
95
+ log.info(color.dim('System packages (Docker, ngrok, Ollama, apt/Homebrew/pixi packages) are left installed.'));
91
96
  }
package/src/ngrok.js CHANGED
@@ -34,9 +34,11 @@ export function tunnels(cfg, platformId = 'linux') {
34
34
  export function selectTunnels(cfg, groups, platformId = 'linux') {
35
35
  const all = tunnels(cfg, platformId);
36
36
  const list = groups.includes('all') ? GROUPS : groups;
37
- const bad = list.filter((g) => !GROUPS.includes(g));
38
- if (bad.length) throw new Error(`Unknown ngrok group: ${bad.join(', ')} (use ${GROUPS.join(', ')} or all)`);
39
- const names = list.flatMap((g) => Object.keys(all[g]));
37
+ // A group (viewers, apps, ...) or a single tunnel by name (ttyd, pwui, app3000, ...).
38
+ const single = Object.assign({}, ...GROUPS.map((g) => all[g]));
39
+ const bad = list.filter((g) => !GROUPS.includes(g) && !single[g]);
40
+ if (bad.length) throw new Error(`Unknown ngrok group or tunnel: ${bad.join(', ')} (use ${GROUPS.join(', ')}, all, or one of ${Object.keys(single).join(', ')})`);
41
+ const names = [...new Set(list.flatMap((g) => (GROUPS.includes(g) ? Object.keys(all[g]) : [g])))];
40
42
  if (!names.length) throw new Error(list.includes('apps') ? 'No app ports: set NGROK_APP_PORTS=3000,5173 in config.env' : 'Nothing to expose');
41
43
  return names;
42
44
  }
@@ -60,3 +62,10 @@ export function renderNgrokYml(cfg, authtoken, platformId = 'linux') {
60
62
  export function renderNgrokEnv(names) {
61
63
  return `HD_NGROK_TUNNELS='${names.join(' ')}'\n`;
62
64
  }
65
+
66
+ /** Names of tunnels that ended up on the same public URL (free plans have one domain). */
67
+ export function sharedUrls(tunnels) {
68
+ const by = {};
69
+ for (const t of tunnels) (by[t.url] = by[t.url] || []).push(t.name);
70
+ return Object.values(by).filter((n) => n.length > 1).flat();
71
+ }
@@ -2,7 +2,7 @@
2
2
  // user logs in, so an unattended reboot needs automatic login (doctor checks).
3
3
  // Agents, not daemons: Claude Code keeps its login in the login Keychain,
4
4
  // which is only unlocked inside the user's session.
5
- // System packages come from Homebrew, run as the user (Homebrew refuses root).
5
+ // System packages come from Homebrew (Apple silicon) or conda-forge via pixi (Intel), as the user.
6
6
 
7
7
  import fs from 'node:fs';
8
8
  import os from 'node:os';
@@ -27,7 +27,7 @@ export const userEnv = (env) => ({ ...env });
27
27
  const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
28
28
 
29
29
  /** A LaunchAgent plist. Every job runs through hd-run, which loads runtime.env. */
30
- export function plist({ label: l, args, keepAlive = true, interval, logFile }) {
30
+ export function plist({ label: l, args, keepAlive = true, interval, logFile, abandon = false }) {
31
31
  return `<?xml version="1.0" encoding="UTF-8"?>
32
32
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33
33
  <plist version="1.0">
@@ -39,7 +39,7 @@ ${args.map((a) => ` <string>${esc(a)}</string>`).join('\n')}
39
39
  </array>
40
40
  <key>RunAtLoad</key><true/>
41
41
  ${keepAlive ? ' <key>KeepAlive</key><true/>\n <key>ThrottleInterval</key><integer>10</integer>\n' : ''}${interval ? ` <key>StartInterval</key><integer>${interval}</integer>\n` : ''} <key>ProcessType</key><string>Interactive</string>
42
- <key>StandardOutPath</key><string>${esc(logFile)}</string>
42
+ ${abandon ? ' <key>AbandonProcessGroup</key><true/>\n' : ''} <key>StandardOutPath</key><string>${esc(logFile)}</string>
43
43
  <key>StandardErrorPath</key><string>${esc(logFile)}</string>
44
44
  </dict>
45
45
  </plist>
@@ -53,19 +53,41 @@ function intervalSeconds(s) {
53
53
  return m[2] && m[2].startsWith('m') ? n * 60 : m[2] === 'h' ? n * 3600 : n;
54
54
  }
55
55
 
56
+ export const LAUNCHABLE = ['harness-tmux', 'harness-chromium', 'harness-ttyd', 'harness-heal', 'harness-ngrok'];
57
+ export const launcherName = (u) => `harness-device-${u.replace(/^harness-/, '')}`;
58
+
59
+ /** Named copies of hd-run (see jobs()), replaced atomically like every script. */
60
+ export function writeLaunchers(ctx, { dryRun }) {
61
+ const src = path.join(ctx.paths.bin, 'hd-run');
62
+ for (const u of LAUNCHABLE) {
63
+ const dest = path.join(ctx.paths.bin, launcherName(u));
64
+ if (dryRun) { console.log(color.dim(` copy hd-run → ${dest}`)); continue; }
65
+ const tmp = `${dest}.new-${process.pid}`;
66
+ fs.copyFileSync(src, tmp);
67
+ fs.chmodSync(tmp, 0o755);
68
+ fs.renameSync(tmp, dest);
69
+ }
70
+ }
71
+
56
72
  /** The job definition of each logical unit. */
57
73
  export function jobs(ctx, detect = true) {
58
74
  const b = (f) => path.join(ctx.paths.bin, f);
59
75
  const logFile = (u) => path.join(ctx.paths.logs, `svc-${u.replace(/^harness-/, '')}.log`);
60
- const ttyd = (detect && which('ttyd', ctx.env)) || '/opt/homebrew/bin/ttyd';
61
- const tmux = (detect && which('tmux', ctx.env)) || '/opt/homebrew/bin/tmux';
76
+ // Intel Macs get them from conda-forge via pixi (~/.pixi/bin): Homebrew dropped Intel.
77
+ const brewBin = process.arch === 'arm64' ? '/opt/homebrew/bin' : path.join(ctx.env.HOME || os.homedir(), '.pixi', 'bin');
78
+ const ttyd = (detect && which('ttyd', ctx.env)) || `${brewBin}/ttyd`;
79
+ const tmux = (detect && which('tmux', ctx.env)) || `${brewBin}/tmux`;
62
80
  const c = ctx.cfg;
81
+ // Each job starts through its own named copy of hd-run, because System
82
+ // Settings → Login Items shows that file's name: harness-device-tmux, ...
83
+ const run = (u) => b(launcherName(u));
63
84
  const def = {
64
- 'harness-tmux': { args: [b('hd-run'), b('hd-tmux-supervise')] },
65
- 'harness-chromium': { args: [b('hd-run'), b('hd-chromium')] },
66
- 'harness-ttyd': { args: [b('hd-run'), ttyd, '-i', 'lo0', '-p', c.TTYD_PORT, '-t', 'titleFixed=harness-device', tmux, 'attach', '-r', '-f', 'ignore-size', '-t', `=${c.SESSION}`] },
67
- 'harness-heal': { args: [b('hd-run'), b('hd-heal')], keepAlive: false, interval: intervalSeconds(c.HEAL_INTERVAL) },
68
- 'harness-ngrok': { args: [b('hd-run'), b('hd-ngrok')] },
85
+ // The tmux server (and every session in it) must outlive this job's restarts.
86
+ 'harness-tmux': { args: [run('harness-tmux'), b('hd-tmux-supervise')], abandon: true },
87
+ 'harness-chromium': { args: [run('harness-chromium'), b('hd-chromium')] },
88
+ 'harness-ttyd': { args: [run('harness-ttyd'), ttyd, '-i', 'lo0', '-p', c.TTYD_PORT, '-t', 'titleFixed=harness-device', tmux, 'attach', '-r', '-f', 'ignore-size', '-t', `=${c.SESSION}`] },
89
+ 'harness-heal': { args: [run('harness-heal'), b('hd-heal')], keepAlive: false, interval: intervalSeconds(c.HEAL_INTERVAL) },
90
+ 'harness-ngrok': { args: [run('harness-ngrok'), b('hd-ngrok')] },
69
91
  };
70
92
  return (u) => {
71
93
  const d = def[u];
@@ -86,6 +108,7 @@ const lc = (args, opts = {}) => run('launchctl', args, { allowFail: true, ...opt
86
108
  const loaded = (l) => ok('launchctl', ['print', `${domain()}/${l}`]);
87
109
 
88
110
  export function activate(ctx, files, { dryRun }) {
111
+ writeLaunchers(ctx, { dryRun });
89
112
  const dir = serviceDir(ctx.env);
90
113
  const ours = (f) => f.startsWith(LABEL_PREFIX) && f.endsWith('.plist');
91
114
  const keep = new Set(Object.keys(files));
@@ -104,11 +127,28 @@ export function activate(ctx, files, { dryRun }) {
104
127
  const isLoaded = !dryRun && loaded(l);
105
128
  // Never reload the tmux job while it runs: the sessions live under it.
106
129
  if (isLoaded && (l === labelOf('harness-tmux') || !changed)) continue;
107
- if (isLoaded) lc(['bootout', `${domain()}/${l}`], { dryRun });
108
- lc(['bootstrap', domain(), file], { dryRun });
130
+ if (isLoaded) {
131
+ lc(['bootout', `${domain()}/${l}`], { dryRun });
132
+ // bootout returns before the job is gone; bootstrapping too early fails with "5: Input/output error".
133
+ for (let i = 0; i < 20 && loaded(l); i++) sleepMs(250);
134
+ }
135
+ bootstrap(file, l, { dryRun });
109
136
  }
110
137
  }
111
138
 
139
+ const sleepMs = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
140
+
141
+ /** launchctl bootstrap, retried while launchd is still tearing down the old job. */
142
+ function bootstrap(file, l, { dryRun }) {
143
+ if (dryRun) return lc(['bootstrap', domain(), file], { dryRun });
144
+ for (let i = 0; i < 5; i++) {
145
+ if (ok('launchctl', ['bootstrap', domain(), file])) return;
146
+ if (loaded(l)) return;
147
+ sleepMs(1000);
148
+ }
149
+ console.log(color.yellow(` ! could not load ${l}; the heal job retries it (or: launchctl bootstrap ${domain()} ${file})`));
150
+ }
151
+
112
152
  export function deactivate(ctx, { dryRun }) {
113
153
  const dir = serviceDir(ctx.env);
114
154
  for (const f of fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.startsWith(LABEL_PREFIX)) : []) {
@@ -116,7 +156,7 @@ export function deactivate(ctx, { dryRun }) {
116
156
  dryRun ? console.log(color.dim(` rm ${f}`)) : fs.rmSync(path.join(dir, f), { force: true });
117
157
  }
118
158
  // The tmux server outlives its supervisor job by design; end it explicitly.
119
- run('tmux', ['kill-session', '-t', `=${ctx.cfg.SESSION}`], { dryRun, allowFail: true });
159
+ run('tmux', ['kill-session', '-t', `=${ctx.cfg.SESSION}`], { dryRun, allowFail: true, env: ctx.env });
120
160
  }
121
161
 
122
162
  export function state(ctx, u) {
@@ -142,18 +182,22 @@ export function followLogsCmd(u, ctx) {
142
182
  export function ngrokUp(ctx) {
143
183
  const file = path.join(serviceDir(ctx.env), plistName('harness-ngrok'));
144
184
  writeFile(file, plist(jobs(ctx)('harness-ngrok')));
145
- lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
185
+ const l = labelOf('harness-ngrok');
186
+ if (loaded(l)) {
187
+ lc(['bootout', `${domain()}/${l}`]);
188
+ for (let i = 0; i < 25 && loaded(l); i++) sleepMs(200);
189
+ }
146
190
  lc(['bootstrap', domain(), file]);
147
191
  }
148
192
 
149
193
  export function ngrokDown(ctx) {
150
- lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
194
+ if (loaded(labelOf('harness-ngrok'))) lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
151
195
  fs.rmSync(path.join(serviceDir(ctx.env), plistName('harness-ngrok')), { force: true });
152
196
  }
153
197
 
154
- /** System packages: Homebrew, as the user. */
198
+ /** System packages: Homebrew, else pixi (conda-forge), as the user. */
155
199
  export function systemSetup(ctx, steps, { dryRun }) {
156
- console.log(`${color.cyan('›')} System setup (Homebrew): ${steps.join(', ')}`);
200
+ console.log(`${color.cyan('›')} System setup (Homebrew or pixi): ${steps.join(', ')}`);
157
201
  run('bash', [path.join(PKG_ROOT, 'sh', 'setup', 'darwin.sh'), '--steps', steps.join(',')], { dryRun, env: ctx.env });
158
202
  }
159
203
 
@@ -121,6 +121,12 @@ export function renderClaudeMd({ cfg }) {
121
121
  This machine is harness device **${cfg.DEVICE}**. Before starting servers, running tests, driving a browser, deploying or changing services, follow the \`harness-device\` skill. Run long-lived processes in tmux windows, not in the foreground.`;
122
122
  }
123
123
 
124
+ /** User-scope MCP servers, as Claude Code stores them (~/.claude.json). */
125
+ export function userMcpServers(env) {
126
+ const file = env.CLAUDE_CONFIG_DIR ? path.join(env.CLAUDE_CONFIG_DIR, '.claude.json') : path.join(env.HOME || os.homedir(), '.claude.json');
127
+ return readJson(file, {}).mcpServers || {};
128
+ }
129
+
124
130
  // harness-device MCP tools that only read, or restart the browser. proc_add,
125
131
  // proc_remove, restart_service and playwright_ui still ask: they start or stop things.
126
132
  export const HARNESS_TOOLS_ALLOWED = ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs',
@@ -145,7 +151,12 @@ export function apply(ctx) {
145
151
 
146
152
  const stateFile = path.join(paths.home, 'claude-permissions.json');
147
153
  const prev = readJson(stateFile, { allow: [], deny: [] });
148
- const mcpNames = ctx.mcpServers.map((s) => s.name);
154
+ // Servers the user registered themselves under the same name are theirs:
155
+ // never replaced. Only names this device registered are re-added or removed.
156
+ const existing = userMcpServers(env);
157
+ const foreign = ctx.mcpServers.filter((s) => existing[s.name] && !(prev.mcp || []).includes(s.name)).map((s) => s.name);
158
+ const mcpNames = ctx.mcpServers.map((s) => s.name).filter((n) => !foreign.includes(n));
159
+ for (const n of foreign) ctx.warn(`You already have an MCP server named "${n}" (user scope); it is left as is, so the device's ${n} server is not registered. To use the device's: claude mcp remove --scope user ${n}, then harness-device install.`);
149
160
 
150
161
  // MCP servers, user scope, re-added so a changed command line takes effect.
151
162
  // Ones this device registered before but no longer has are removed.
@@ -155,7 +166,7 @@ export function apply(ctx) {
155
166
  for (const name of (prev.mcp || []).filter((n) => !mcpNames.includes(n))) {
156
167
  run('claude', ['mcp', 'remove', '--scope', 'user', name], { dryRun, allowFail: true, env });
157
168
  }
158
- for (const s of ctx.mcpServers) {
169
+ for (const s of ctx.mcpServers.filter((x) => mcpNames.includes(x.name))) {
159
170
  run('claude', ['mcp', 'remove', '--scope', 'user', s.name], { dryRun, allowFail: true, env });
160
171
  run('claude', ['mcp', 'add', '--scope', 'user', s.name, '--', s.command, ...(s.args || [])], { dryRun, env });
161
172
  }
@@ -179,14 +190,15 @@ export function apply(ctx) {
179
190
  const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
180
191
  writeFile(f.settings, JSON.stringify(settings, null, 2) + '\n', { dryRun });
181
192
  writeFile(stateFile, JSON.stringify({ ...added, ...keep, mcp: mcpNames }, null, 2) + '\n', { dryRun });
182
- return { allow, deny, added };
193
+ return { allow, deny, added, registered: mcpNames, skipped: foreign };
183
194
  }
184
195
 
185
196
  export function remove(ctx) {
186
197
  const { env, dryRun, paths } = ctx;
187
198
  const f = files(env);
199
+ // Only what this device registered: never a server of the user's with the same name.
188
200
  const registered = readJson(path.join(paths.home, 'claude-permissions.json'), {}).mcp || [];
189
- for (const name of new Set([...ctx.mcpServers.map((s) => s.name), ...registered])) run('claude', ['mcp', 'remove', '--scope', 'user', name], { dryRun, allowFail: true, env });
201
+ for (const name of registered) run('claude', ['mcp', 'remove', '--scope', 'user', name], { dryRun, allowFail: true, env });
190
202
  if (fs.existsSync(f.skill)) dryRun ? console.log(` rm ${f.skill}`) : fs.rmSync(path.dirname(f.skill), { recursive: true, force: true });
191
203
  if (fs.existsSync(f.claudeMd)) writeFile(f.claudeMd, removeBlock(fs.readFileSync(f.claudeMd, 'utf8')), { dryRun });
192
204
  const stateFile = path.join(paths.home, 'claude-permissions.json');
package/src/state.js CHANGED
@@ -43,7 +43,7 @@ export function transcriptOf(id, env = process.env) {
43
43
  }
44
44
 
45
45
  export function listSessions(ctx) {
46
- const wins = capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}']).split('\n');
46
+ const wins = capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}'], { env: ctx.env }).split('\n');
47
47
  const out = [];
48
48
  for (const p of ctx.projects) {
49
49
  if (ctx.cfg.SERVE_MODE === 'server') {
@@ -131,7 +131,7 @@ export function removeSlot(ctx, project, slot) {
131
131
  fs.rmSync(f);
132
132
  fs.rmSync(`${f}.failing`, { force: true });
133
133
  event(ctx, `${project}/${slot} removed (conversation ${id} kept on disk)`);
134
- ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:${windowName(project, slot)}`]);
134
+ ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:${windowName(project, slot)}`], { env: ctx.env });
135
135
  return { id };
136
136
  }
137
137
 
@@ -155,13 +155,13 @@ export function removeProc(ctx, name) {
155
155
  fs.rmSync(path.join(d, `${name}.cmd`));
156
156
  fs.rmSync(path.join(d, `${name}.dir`), { force: true });
157
157
  event(ctx, `proc ${name} removed`);
158
- ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:proc-${name}`]);
158
+ ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:proc-${name}`], { env: ctx.env });
159
159
  }
160
160
 
161
161
  export function listProcs(ctx) {
162
162
  const d = path.join(ctx.paths.state, 'procs');
163
163
  if (!fs.existsSync(d)) return [];
164
- const wins = capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}']).split('\n');
164
+ const wins = capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}'], { env: ctx.env }).split('\n');
165
165
  return fs.readdirSync(d).filter((f) => f.endsWith('.cmd')).map((f) => {
166
166
  const name = f.slice(0, -4);
167
167
  return {
@@ -184,7 +184,7 @@ export function recentEvents(ctx, n = 30) {
184
184
  * with none, the unit is restarted so the server is owned by systemd.
185
185
  */
186
186
  export function applyLayout(ctx) {
187
- if (ok('tmux', ['has-session', '-t', `=${ctx.cfg.SESSION}`])) {
187
+ if (ok('tmux', ['has-session', '-t', `=${ctx.cfg.SESSION}`], { env: ctx.env })) {
188
188
  run(path.join(ctx.paths.bin, 'hd-tmux-layout'), [], { env: ctx.env, allowFail: true });
189
189
  } else {
190
190
  ctx.platform.restart(ctx, 'harness-tmux');
@@ -192,6 +192,6 @@ export function applyLayout(ctx) {
192
192
  }
193
193
 
194
194
  function restartWindow(ctx, win) {
195
- ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:${win}`]);
195
+ ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:${win}`], { env: ctx.env });
196
196
  if (fs.existsSync(path.join(ctx.paths.bin, 'hd-tmux-layout'))) applyLayout(ctx);
197
197
  }