@dreamtree-org/harness-device 0.1.0 → 0.1.1

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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1
4
+
5
+ Fixes from the first installs on a real Mac (Intel) and checks on Ubuntu 26.04.
6
+
7
+ - **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.
8
+ - **Intel Macs:** Homebrew no longer supports them, so setup installs tmux, ttyd and jq from conda-forge through pixi (per user, no sudo).
9
+ - **Docker on macOS:** uses Docker Desktop when it is installed, instead of adding colima next to it.
10
+ - **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.
11
+ - **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`).
12
+ - **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.
13
+ - **Heal no longer restarts a browser that is still starting** (first minute after a start).
14
+ - **Login Items** names each service (`harness-device-tmux`, `-chromium`, `-ttyd`, `-heal`) instead of four `hd-run` entries.
15
+ - **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.
16
+
3
17
  ## 0.1.0
4
18
 
5
19
  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
 
@@ -161,11 +161,11 @@ Pick them with `init --with`/`--without`, or edit `CAPABILITIES=` in `config.env
161
161
  | `browser` | Playwright Chromium | Playwright Chromium | One persistent Chromium on CDP 127.0.0.1:9222 |
162
162
  | `playwright` | | | Playwright MCP attached to that browser; `hd-pw-live` headed runs and UI mode |
163
163
  | `sqlite` | apt `sqlite3` | built in | `sqlite3` |
164
- | `docker` | Docker Engine (`get.docker.com`) | colima + docker CLI | `docker`, `docker compose` |
164
+ | `docker` | Docker Engine (`get.docker.com`) | Docker Desktop, else colima | `docker`, `docker compose` |
165
165
  | `dokploy` | API only | API only | Dokploy MCP against your deployment (`DOKPLOY_URL` + `secrets set DOKPLOY_API_KEY`); nothing is installed |
166
166
  | `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) |
167
+ | `ngrok` | apt repo | Homebrew (Intel: ngrok.com download) | Tunnels you open; the agent may only read them |
168
+ | `ollama` | ollama.com script | Homebrew (Intel: Ollama app) | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
169
169
 
170
170
  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
171
 
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.1",
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,18 @@ 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
+ has brew || die "install ngrok from https://ngrok.com/download (put it on your PATH), then re-run install"
98
+ brew install ngrok
99
+ fi
68
100
  fi
69
101
 
70
102
  if want ollama; then
71
- has ollama || brew_install ollama
72
- brew services start ollama >/dev/null 2>&1 || true
103
+ if ! has ollama; then
104
+ has brew || die "install Ollama from https://ollama.com/download (the app starts at login), then re-run install"
105
+ brew install ollama
106
+ brew services start ollama >/dev/null 2>&1 || true
107
+ fi
73
108
  fi
74
109
 
75
110
  log "system steps done: $STEPS"
@@ -53,7 +53,7 @@ export const CAPABILITIES = {
53
53
  const out = [];
54
54
  out.push({ name: 'tmux', ok: !!which('tmux', ctx.env), fix: 'harness-device install' });
55
55
  const s = ctx.cfg.SESSION;
56
- const has = ok('tmux', ['has-session', '-t', `=${s}`]);
56
+ const has = ok('tmux', ['has-session', '-t', `=${s}`], { env: ctx.env });
57
57
  out.push({ name: `tmux session ${s}`, ok: has, fix: 'harness-device restart tmux' });
58
58
  if (has) {
59
59
  for (const x of listSessions(ctx)) {
@@ -146,15 +146,15 @@ One Chromium runs on the display with a persistent profile: logins, cookies and
146
146
  },
147
147
 
148
148
  docker: {
149
- label: 'Docker (Linux: Docker Engine; macOS: colima + docker CLI)',
149
+ label: 'Docker (Linux: Docker Engine; macOS: Docker Desktop if installed, else colima)',
150
150
  system: ['docker'],
151
151
  allow: ['Bash(docker:*)', 'Bash(colima status:*)'],
152
152
  checks: (ctx) => [
153
153
  { 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' },
154
+ { 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
155
  ],
156
156
  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.`,
157
+ 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
158
  },
159
159
 
160
160
  dokploy: {
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
  }
package/src/config.js CHANGED
@@ -221,7 +221,7 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
221
221
  // Services start with a bare PATH; keep the one the installer ran with, so
222
222
  // `claude`, `node`, `npx`, nvm/volta and Homebrew installs resolve the same way.
223
223
  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'] : []),
224
+ ...(platformId === 'darwin' ? [path.join(env.HOME || os.homedir(), '.pixi', 'bin'), '/opt/homebrew/bin', '/usr/local/bin'] : []),
225
225
  ...String(env.PATH || '/usr/local/bin:/usr/bin:/bin').split(':')])].filter(Boolean).join(':'),
226
226
  TERM: 'xterm-256color',
227
227
  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.
@@ -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
  }
@@ -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,9 +127,26 @@ 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 });
136
+ }
137
+ }
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);
109
148
  }
149
+ console.log(color.yellow(` ! could not load ${l}; the heal job retries it (or: launchctl bootstrap ${domain()} ${file})`));
110
150
  }
111
151
 
112
152
  export function deactivate(ctx, { dryRun }) {
@@ -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) {
@@ -151,9 +191,9 @@ export function ngrokDown(ctx) {
151
191
  fs.rmSync(path.join(serviceDir(ctx.env), plistName('harness-ngrok')), { force: true });
152
192
  }
153
193
 
154
- /** System packages: Homebrew, as the user. */
194
+ /** System packages: Homebrew, else pixi (conda-forge), as the user. */
155
195
  export function systemSetup(ctx, steps, { dryRun }) {
156
- console.log(`${color.cyan('›')} System setup (Homebrew): ${steps.join(', ')}`);
196
+ console.log(`${color.cyan('›')} System setup (Homebrew or pixi): ${steps.join(', ')}`);
157
197
  run('bash', [path.join(PKG_ROOT, 'sh', 'setup', 'darwin.sh'), '--steps', steps.join(',')], { dryRun, env: ctx.env });
158
198
  }
159
199
 
@@ -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
  }
@@ -185,8 +196,9 @@ export function apply(ctx) {
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
  }