@dreamtree-org/harness-device 0.0.0-stage → 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.
Files changed (45) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +255 -2
  4. package/bin/harness-device.js +8 -0
  5. package/package.json +62 -4
  6. package/sh/bin/hd-chromium +51 -0
  7. package/sh/bin/hd-heal +33 -0
  8. package/sh/bin/hd-lib.sh +97 -0
  9. package/sh/bin/hd-ngrok +7 -0
  10. package/sh/bin/hd-proc-loop +23 -0
  11. package/sh/bin/hd-pw-live +33 -0
  12. package/sh/bin/hd-rc-loop +42 -0
  13. package/sh/bin/hd-run +6 -0
  14. package/sh/bin/hd-serve-claude +23 -0
  15. package/sh/bin/hd-tmux-layout +71 -0
  16. package/sh/bin/hd-tmux-supervise +16 -0
  17. package/sh/bin/hd-with-secrets +8 -0
  18. package/sh/setup/darwin.sh +110 -0
  19. package/sh/setup/linux.sh +118 -0
  20. package/src/capabilities.js +237 -0
  21. package/src/cli.js +383 -0
  22. package/src/config.js +239 -0
  23. package/src/context.js +66 -0
  24. package/src/device.js +127 -0
  25. package/src/doctor.js +40 -0
  26. package/src/fleet.js +94 -0
  27. package/src/install.js +96 -0
  28. package/src/mcp/server.js +115 -0
  29. package/src/ngrok.js +62 -0
  30. package/src/platform/darwin.js +230 -0
  31. package/src/platform/index.js +12 -0
  32. package/src/platform/linux.js +142 -0
  33. package/src/providers/claude.js +224 -0
  34. package/src/state.js +197 -0
  35. package/src/util.js +103 -0
  36. package/templates/systemd/harness-chromium.service +17 -0
  37. package/templates/systemd/harness-heal.service +7 -0
  38. package/templates/systemd/harness-heal.timer +10 -0
  39. package/templates/systemd/harness-ngrok.service +13 -0
  40. package/templates/systemd/harness-novnc.service +14 -0
  41. package/templates/systemd/harness-tmux.service +15 -0
  42. package/templates/systemd/harness-ttyd.service +14 -0
  43. package/templates/systemd/harness-vnc.service +14 -0
  44. package/templates/systemd/harness-xvfb.service +13 -0
  45. package/templates/systemd/harness.target +6 -0
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env bash
2
+ # Serves one project session slot to the remote agent forever, restarting with
3
+ # backoff. The provider decides how: hd-serve-<provider>.
4
+ # Usage: hd-rc-loop <project> <dir> <slot|-> ("-" = server mode, no slot)
5
+ set -u
6
+ . "$(dirname "$0")/hd-lib.sh"
7
+ name="$1"; dir="$2"; slot="$3"
8
+ hd_strip_anthropic
9
+ cd "$dir" || { hd_log "project dir $dir is missing; retrying in 60s"; sleep 60; exit 1; }
10
+ label="${HD_DEVICE:-device}-$name"; [ "$slot" = - ] || [ "$slot" = 1 ] || label="$label-$slot"
11
+ slotf="$HD_STATE/sessions/$name/$slot"
12
+
13
+ delay=2; fast=0
14
+ while true; do
15
+ [ "$slot" = - ] || [ -f "$slotf" ] || { hd_log "slot $name/$slot was removed; stopping"; exit 0; }
16
+ started=$(date +%s)
17
+ if [ "$slot" = - ]; then
18
+ hd_log "serving $name ($dir) as $label [server mode]"
19
+ "$(dirname "$0")/hd-serve-${HD_PROVIDER:-claude}" "$label" -
20
+ else
21
+ id=$(cat "$slotf")
22
+ hd_log "serving $name/$slot ($dir) as $label, conversation $id"
23
+ "$(dirname "$0")/hd-serve-${HD_PROVIDER:-claude}" "$label" "$id"
24
+ fi
25
+ code=$?
26
+ ran=$(( $(date +%s) - started ))
27
+ if [ "$ran" -ge 300 ]; then delay=2; fast=0; else delay=$(( delay * 2 )); fast=$(( fast + 1 )); [ "$delay" -gt 300 ] && delay=300; fi
28
+ # Never swap the conversation automatically: a fast failure is usually a
29
+ # login or network problem, and the pinned conversation must survive it.
30
+ # Flag the slot instead; doctor and status report it, and
31
+ # `harness-device session reset <project> [slot]` starts a new one on purpose.
32
+ if [ "$slot" != - ]; then
33
+ if [ "$fast" -ge 5 ]; then
34
+ [ -f "$slotf.failing" ] || hd_event "$name/$slot failing: $fast quick exits in a row (last code $code)"
35
+ echo "$code $(date +%s)" > "$slotf.failing"
36
+ elif [ "$fast" -eq 0 ]; then
37
+ rm -f "$slotf.failing"
38
+ fi
39
+ fi
40
+ hd_log "exited with $code after ${ran}s; restarting in ${delay}s (Ctrl-C now to stop this loop)"
41
+ sleep "$delay"
42
+ done
package/sh/bin/hd-run ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ # Run a command with runtime.env loaded (PATH, ports, HD_*). launchd jobs on
3
+ # macOS start through this; systemd units use EnvironmentFile= instead.
4
+ set -eu
5
+ . "$(dirname "$0")/hd-lib.sh"
6
+ exec "$@"
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env bash
2
+ # Provider "claude". Usage: hd-serve-claude <session-name> <conversation-id|->
3
+ #
4
+ # conversation mode (an id): an interactive Claude Code session with Remote
5
+ # Control on, pinned to one conversation id. The first start creates the
6
+ # conversation with that id; every later start (crash, reboot, days of
7
+ # downtime) resumes it from its transcript on disk and reattaches it to
8
+ # Remote Control, so the remote session continues where it stopped.
9
+ # server mode (-): `claude remote-control`, many on-demand sessions; Claude
10
+ # Code itself restores them only if it restarts within about 4 hours.
11
+ set -u
12
+ . "$(dirname "$0")/hd-lib.sh"
13
+ command -v claude >/dev/null 2>&1 || { echo "claude is not on PATH (install: curl -fsSL https://claude.ai/install.sh | bash)"; exit 127; }
14
+ name="$1"; id="${2:--}"
15
+ if [ "$id" = - ]; then
16
+ exec claude remote-control --name "$name"
17
+ fi
18
+ if [ -n "$(hd_claude_transcript "$id")" ]; then
19
+ hd_event "$name resume $id"
20
+ exec claude --remote-control "$name" --resume "$id"
21
+ else
22
+ exec claude --remote-control "$name" --session-id "$id"
23
+ fi
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env bash
2
+ # Idempotent: builds the tmux session from saved state and nothing else, so a
3
+ # reboot (or a killed session) comes back exactly as it was.
4
+ # rc-<project>[-<slot>] one window per saved session slot (conversation mode)
5
+ # or per project (server mode), running hd-rc-loop
6
+ # proc-<name> one window per registered long-running process
7
+ # Windows whose state was removed are closed. Safe to run any time.
8
+ set -euo pipefail
9
+ . "$(dirname "$0")/hd-lib.sh"
10
+ s="$HD_SESSION"
11
+ bin="$HD_HOME/bin"
12
+ mode="${HD_SERVE_MODE:-conversation}"
13
+
14
+ if ! tmux has-session -t "=$s" 2>/dev/null; then
15
+ tmux new-session -d -s "$s" -n home -c "$HOME" -x 220 -y 50
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
20
+ hd_log "created tmux session $s"
21
+ fi
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
23
+
24
+ want=" "
25
+ existing=$(tmux list-windows -t "=$s" -F '#{window_name}')
26
+ ensure() { # ensure <window> <dir> <logfile> <command...>
27
+ local win="$1" dir="$2" logf="$3"; shift 3
28
+ want="$want$win "
29
+ grep -qxF "$win" <<<"$existing" && return 0
30
+ local cmd; cmd=$(printf '%q ' "$@")
31
+ tmux new-window -d -t "=$s:" -n "$win" -c "$dir" "$cmd"
32
+ tmux pipe-pane -t "=$s:$win" -o "cat >> $(printf '%q' "$logf")"
33
+ hd_log "started window $win"
34
+ }
35
+
36
+ if [ -f "$HD_HOME/projects.tsv" ]; then
37
+ while IFS=$'\t' read -r name dir; do
38
+ [ -n "${name:-}" ] || continue
39
+ if [ "$mode" = server ]; then
40
+ ensure "rc-$name" "$dir" "$HD_HOME/logs/rc-$name.log" "$bin/hd-rc-loop" "$name" "$dir" "-"
41
+ continue
42
+ fi
43
+ sdir="$HD_STATE/sessions/$name"
44
+ mkdir -p "$sdir"
45
+ # Every project has at least slot 1; its conversation id is created once
46
+ # and then reused on every start, which is what makes restores possible.
47
+ if [ -z "$(ls "$sdir" 2>/dev/null | grep -E '^[0-9]+$' || true)" ]; then
48
+ hd_uuid > "$sdir/1"
49
+ hd_event "$name/1 new conversation $(cat "$sdir/1")"
50
+ fi
51
+ for slotf in $(ls "$sdir" | grep -E '^[0-9]+$' | sort -n); do
52
+ win="rc-$name"; [ "$slotf" = 1 ] || win="rc-$name-$slotf"
53
+ ensure "$win" "$dir" "$HD_HOME/logs/$win.log" "$bin/hd-rc-loop" "$name" "$dir" "$slotf"
54
+ done
55
+ done < "$HD_HOME/projects.tsv"
56
+ fi
57
+
58
+ if [ -d "$HD_STATE/procs" ]; then
59
+ for cmdf in "$HD_STATE"/procs/*.cmd; do
60
+ [ -e "$cmdf" ] || continue
61
+ pname=$(basename "$cmdf" .cmd)
62
+ pdir=$(cat "$HD_STATE/procs/$pname.dir" 2>/dev/null || echo "$HOME")
63
+ ensure "proc-$pname" "$pdir" "$HD_HOME/logs/proc-$pname.log" "$bin/hd-proc-loop" "$pname"
64
+ done
65
+ fi
66
+
67
+ while read -r win; do
68
+ case "$win" in
69
+ rc-*|proc-*) case "$want" in *" $win "*) ;; *) tmux kill-window -t "=$s:$win"; hd_log "closed window $win (removed)" ;; esac ;;
70
+ esac
71
+ done <<<"$(tmux list-windows -t "=$s" -F '#{window_name}')"
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env bash
2
+ # macOS launchd job for the tmux session (KeepAlive). Builds the session from
3
+ # saved state, then stays alive while it exists; if the session disappears it
4
+ # exits and launchd starts it again, which rebuilds it. (Linux runs
5
+ # hd-tmux-layout from a oneshot systemd unit instead.)
6
+ set -u
7
+ . "$(dirname "$0")/hd-lib.sh"
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
15
+ hd_log "tmux session $HD_SESSION is gone; exiting so launchd rebuilds it"
16
+ exit 1
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ # Run a command with ~/.harness-device/secrets.env loaded, so MCP servers get
3
+ # their API keys without the keys being copied into the agent's own config.
4
+ # Usage: hd-with-secrets <command> [args...]
5
+ set -eu
6
+ . "$(dirname "$0")/hd-lib.sh"
7
+ hd_load_secrets
8
+ exec "$@"
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bash
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.
6
+ # darwin.sh --steps base,display,playwright-deps,sqlite,docker,ngrok,ollama
7
+ # Every step is idempotent: it checks first and skips what is already there.
8
+ set -euo pipefail
9
+
10
+ STEPS="base"
11
+ while [ $# -gt 0 ]; do
12
+ case "$1" in
13
+ --steps) STEPS="$2"; shift 2 ;;
14
+ *) echo "unknown argument: $1" >&2; exit 2 ;;
15
+ esac
16
+ done
17
+
18
+ log() { printf '\033[1;36m[harness-device setup]\033[0m %s\n' "$*"; }
19
+ die() { printf '\033[1;31m[harness-device setup]\033[0m %s\n' "$*" >&2; exit 1; }
20
+ has() { command -v "$1" >/dev/null 2>&1; }
21
+ want() { case ",$STEPS," in *",$1,"*) return 0 ;; *) return 1 ;; esac; }
22
+
23
+ [ "$(uname -s)" = Darwin ] || die "this script is for macOS"
24
+ [ "$(id -u)" -ne 0 ] || die "run as your user, not root"
25
+ for b in /opt/homebrew/bin/brew /usr/local/bin/brew; do [ -x "$b" ] && eval "$("$b" shellenv)" && break; done
26
+ PIXI_HOME="${PIXI_HOME:-$HOME/.pixi}"
27
+ export PATH="$PIXI_HOME/bin:$PATH"
28
+
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() {
44
+ local missing=()
45
+ for p in "$@"; do has "$p" || missing+=("$p"); done
46
+ [ ${#missing[@]} -eq 0 ] && return 0
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
54
+ }
55
+
56
+ if want base; then
57
+ pkg_install tmux jq git
58
+ fi
59
+
60
+ if want display; then
61
+ # The Mac's own screen is the display; ttyd serves the read-only tmux view.
62
+ pkg_install ttyd
63
+ log "to watch the screen remotely, turn on System Settings → General → Sharing → Screen Sharing (used over the SSH tunnel)"
64
+ fi
65
+
66
+ if want playwright-deps; then
67
+ : # Chromium needs no extra system libraries on macOS.
68
+ fi
69
+
70
+ if want sqlite; then
71
+ has sqlite3 || die "sqlite3 is missing (it ships with macOS): reinstall the Xcode command-line tools"
72
+ fi
73
+
74
+ if want docker; then
75
+ # Docker Engine needs a Linux VM on macOS: Docker Desktop if installed, else colima.
76
+ if has docker && docker info >/dev/null 2>&1; then
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"
85
+ else
86
+ brew install colima docker docker-compose
87
+ mkdir -p "$HOME/.docker/cli-plugins"
88
+ ln -sfn "$(brew --prefix)/opt/docker-compose/bin/docker-compose" "$HOME/.docker/cli-plugins/docker-compose"
89
+ # brew services = a LaunchAgent: colima comes back at every login.
90
+ brew services start colima
91
+ log "colima started (first start downloads its VM image; docker works once it is up)"
92
+ fi
93
+ fi
94
+
95
+ if want ngrok; then
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
100
+ fi
101
+
102
+ if want ollama; then
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
108
+ fi
109
+
110
+ log "system steps done: $STEPS"
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env bash
2
+ # harness-device system setup for Linux (apt). Run by `harness-device install` through sudo.
3
+ # linux.sh --user <name> --steps base,display,playwright-deps,sqlite,docker,ngrok,ollama
4
+ # Every step is idempotent: it checks first and skips what is already there.
5
+ set -euo pipefail
6
+
7
+ USER_NAME=""; STEPS="base"; NPX=npx
8
+ while [ $# -gt 0 ]; do
9
+ case "$1" in
10
+ --user) USER_NAME="$2"; shift 2 ;;
11
+ --steps) STEPS="$2"; shift 2 ;;
12
+ # The user's npx (nvm/volta installs are not on root's PATH).
13
+ --npx) NPX="$2"; shift 2 ;;
14
+ *) echo "unknown argument: $1" >&2; exit 2 ;;
15
+ esac
16
+ done
17
+
18
+ log() { printf '\033[1;36m[harness-device root]\033[0m %s\n' "$*"; }
19
+ die() { printf '\033[1;31m[harness-device root]\033[0m %s\n' "$*" >&2; exit 1; }
20
+ has() { command -v "$1" >/dev/null 2>&1; }
21
+ want() { case ",$STEPS," in *",$1,"*) return 0 ;; *) return 1 ;; esac; }
22
+
23
+ [ "$(id -u)" -eq 0 ] || die "must run as root"
24
+ [ -n "$USER_NAME" ] && id "$USER_NAME" >/dev/null 2>&1 || die "--user must name an existing user"
25
+ has apt-get || die "only Debian/Ubuntu (apt) servers are supported"
26
+ export DEBIAN_FRONTEND=noninteractive
27
+
28
+ APT_UPDATED=0
29
+ apt_install() {
30
+ local missing=()
31
+ for p in "$@"; do dpkg -s "$p" >/dev/null 2>&1 || missing+=("$p"); done
32
+ [ ${#missing[@]} -eq 0 ] && return 0
33
+ if [ "$APT_UPDATED" -eq 0 ]; then apt-get update -qq; APT_UPDATED=1; fi
34
+ log "apt install ${missing[*]}"
35
+ apt-get install -y -qq --no-install-recommends "${missing[@]}"
36
+ }
37
+
38
+ if want base; then
39
+ apt_install ca-certificates curl gnupg jq tmux iproute2 git
40
+ # Linger: the user's systemd manager (and so every harness service) starts
41
+ # at boot, without anyone logging in.
42
+ if [ "$(loginctl show-user "$USER_NAME" -p Linger --value 2>/dev/null || echo no)" != yes ]; then
43
+ log "enabling linger for $USER_NAME"
44
+ loginctl enable-linger "$USER_NAME"
45
+ fi
46
+ fi
47
+
48
+ if want display; then
49
+ apt_install xvfb x11vnc novnc websockify imagemagick fonts-liberation fonts-noto-color-emoji xauth dbus-x11
50
+ if ! has ttyd; then
51
+ if apt-cache show ttyd >/dev/null 2>&1; then
52
+ apt_install ttyd
53
+ else
54
+ arch=$(uname -m); case "$arch" in x86_64|aarch64) ;; *) die "no ttyd package or release binary for $arch" ;; esac
55
+ log "ttyd is not packaged here; installing the release binary from github.com/tsl0922/ttyd"
56
+ curl -fsSL -o /usr/local/bin/ttyd "https://github.com/tsl0922/ttyd/releases/latest/download/ttyd.$arch"
57
+ chmod 755 /usr/local/bin/ttyd
58
+ fi
59
+ fi
60
+ fi
61
+
62
+ if want sqlite; then
63
+ apt_install sqlite3
64
+ fi
65
+
66
+ if want playwright-deps; then
67
+ log "installing Chromium system libraries (playwright install-deps chromium)"
68
+ PATH="$(dirname "$NPX"):$PATH" "$NPX" -y playwright@latest install-deps chromium
69
+ fi
70
+
71
+ if want docker; then
72
+ if has docker; then
73
+ log "docker already installed ($(docker --version))"
74
+ else
75
+ log "installing Docker Engine (get.docker.com)"
76
+ curl -fsSL https://get.docker.com | sh
77
+ fi
78
+ systemctl enable --now docker >/dev/null
79
+ if ! id -nG "$USER_NAME" | tr ' ' '\n' | grep -qx docker; then
80
+ usermod -aG docker "$USER_NAME"
81
+ log "added $USER_NAME to the docker group"
82
+ # The user's systemd manager (parent of every harness service and of the
83
+ # tmux server Claude runs in) only picks up new groups when it restarts.
84
+ # Restarting it ends every live session (they resume, but an agent running
85
+ # this install would be cut off mid-way), so only do it when none run.
86
+ uid=$(id -u "$USER_NAME")
87
+ if runuser -u "$USER_NAME" -- env XDG_RUNTIME_DIR="/run/user/$uid" systemctl --user is-active --quiet harness-tmux 2>/dev/null; then
88
+ log "sessions are running, so the docker group applies after the next reboot (or: sudo systemctl restart user@$uid.service, then sessions resume)"
89
+ else
90
+ systemctl try-restart "user@$uid.service" || true
91
+ log "restarted $USER_NAME's systemd user manager so services get the docker group (your SSH shell needs a re-login)"
92
+ fi
93
+ fi
94
+ fi
95
+
96
+ if want ngrok; then
97
+ if has ngrok; then
98
+ log "ngrok already installed"
99
+ else
100
+ log "installing ngrok agent (official apt repository)"
101
+ curl -fsSL https://ngrok-agent.s3.amazonaws.com/ngrok.asc -o /etc/apt/trusted.gpg.d/ngrok.asc
102
+ echo "deb https://ngrok-agent.s3.amazonaws.com bookworm main" > /etc/apt/sources.list.d/ngrok.list
103
+ APT_UPDATED=0
104
+ apt_install ngrok
105
+ fi
106
+ fi
107
+
108
+ if want ollama; then
109
+ if has ollama; then
110
+ log "ollama already installed"
111
+ else
112
+ log "installing Ollama (ollama.com/install.sh); it listens on 127.0.0.1:11434"
113
+ curl -fsSL https://ollama.com/install.sh | sh
114
+ fi
115
+ systemctl enable --now ollama >/dev/null 2>&1 || true
116
+ fi
117
+
118
+ log "system steps done: $STEPS"
@@ -0,0 +1,237 @@
1
+ // What a device can give a remote agent. Each capability says what it needs
2
+ // installed (system steps and user steps), which services it owns on each
3
+ // platform, how to check it, which MCP servers it adds, which commands are
4
+ // pre-approved, and how to explain it to the agent (a section of the skill).
5
+ //
6
+ // Providers (src/providers/*) turn the MCP / allow / docs parts into their own
7
+ // formats; platforms (src/platform/*) turn services into systemd or launchd.
8
+ // Capabilities know neither which agent nor which OS is on the other side,
9
+ // beyond the per-platform `units` lists and `plat` passed to docs().
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { ok, httpOk, httpJson, which } from './util.js';
14
+ import { listSessions, listProcs } from './state.js';
15
+
16
+ export const PLAYWRIGHT_MCP = '@playwright/mcp@0.0.86';
17
+ export const DOKPLOY_MCP = '@dokploy/mcp@0.30.7';
18
+
19
+ const isMac = (plat) => plat && plat.id === 'darwin';
20
+
21
+ async function dokployApi(url, key) {
22
+ try {
23
+ const res = await fetch(`${url.replace(/\/+$/, '')}/api/project.all`, { headers: { 'x-api-key': key }, signal: AbortSignal.timeout(8000) });
24
+ return res.status;
25
+ } catch {
26
+ return 0;
27
+ }
28
+ }
29
+
30
+ /** @type {Record<string, any>} */
31
+ export const CAPABILITIES = {
32
+ shell: {
33
+ label: 'Native shell + tmux, persistent agent sessions per project',
34
+ required: true,
35
+ system: ['base'],
36
+ units: { linux: ['harness-tmux'], darwin: ['harness-tmux'] },
37
+ allow: [
38
+ 'Bash(git:*)', 'Bash(npm:*)', 'Bash(npx:*)', 'Bash(node:*)', 'Bash(tmux:*)', 'Bash(curl:*)',
39
+ // No cat/grep/find here: they would read secrets past the Read() denies.
40
+ // Claude's own Read/Grep/Glob tools cover them and respect those denies.
41
+ 'Bash(harness-device status:*)', 'Bash(harness-device doctor:*)', 'Bash(harness-device session list:*)',
42
+ 'Bash(harness-device session new:*)', 'Bash(harness-device proc list:*)', 'Bash(harness-device logs:*)',
43
+ 'Bash(harness-device events:*)', 'Bash(harness-device tunnel:*)', 'Bash(harness-device ngrok status:*)',
44
+ 'Bash(ls:*)', 'Bash(jq:*)', 'Bash(which:*)',
45
+ ],
46
+ deny: [
47
+ 'Bash(sudo:*)', 'Bash(su:*)', 'Bash(shutdown:*)', 'Bash(reboot:*)', 'Bash(mkfs:*)', 'Bash(dd:*)',
48
+ // The tmux server holds every live session, this one included.
49
+ 'Bash(tmux kill-server:*)', 'Bash(tmux kill-session:*)',
50
+ 'Bash(rm -rf /)', 'Bash(rm -rf /*)', 'Bash(rm -rf ~)', 'Bash(rm -rf ~/*)', 'Bash(rm -rf $HOME)',
51
+ ],
52
+ checks: (ctx) => {
53
+ const out = [];
54
+ out.push({ name: 'tmux', ok: !!which('tmux', ctx.env), fix: 'harness-device install' });
55
+ const s = ctx.cfg.SESSION;
56
+ const has = ok('tmux', ['has-session', '-t', `=${s}`], { env: ctx.env });
57
+ out.push({ name: `tmux session ${s}`, ok: has, fix: 'harness-device restart tmux' });
58
+ if (has) {
59
+ for (const x of listSessions(ctx)) {
60
+ const t = x.id ? (x.transcript ? `resumes ${x.id.slice(0, 8)}…` : `new conversation ${x.id.slice(0, 8)}… (no transcript yet)`) : 'server mode';
61
+ out.push({ name: `session ${x.name}`, ok: x.running && !x.failing, msg: x.failing ? `keeps exiting: harness-device logs ${x.window}` : t, fix: x.failing ? `harness-device logs ${x.window} (if the conversation itself is broken: harness-device session reset ${x.project} ${x.slot})` : 'hd-heal' });
62
+ }
63
+ for (const pr of listProcs(ctx)) out.push({ name: `proc ${pr.name}`, ok: pr.running, msg: pr.command, fix: 'hd-heal' });
64
+ }
65
+ return out;
66
+ },
67
+ docs: (cfg) => `## Shell, tmux, and surviving restarts
68
+ You run on device **${cfg.DEVICE}**. Native commands run through your Bash tool directly on this machine. Each project session runs in tmux session \`${cfg.SESSION}\`, window \`rc-<project>\` (extra slots: \`rc-<project>-<n>\`).
69
+ ${cfg.SERVE_MODE === 'server'
70
+ ? '- Sessions are served by `claude remote-control` (server mode). After a restart they come back only if the device was down for less than about 4 hours.'
71
+ : '- **This conversation is pinned.** If the device reboots, crashes or loses power, the harness resumes this exact conversation from its transcript and reattaches it to Remote Control, however long the device was down. Save work in files and commits as you go, not only in memory.'}
72
+ - **Anything that must keep running goes in a registered process, not your foreground**: \`harness-device proc add <name> <dir> '<command>'\` (dev servers, watchers, workers). It runs in tmux window \`proc-<name>\`, restarts if it crashes, and comes back after a reboot. Output: \`harness-device logs proc-<name>\`. Remove it when done: \`harness-device proc rm <name>\`. List: \`harness-device proc list\`.
73
+ - A one-off process that only needs to outlive this turn can go in a plain window: \`tmux new-window -d -t ${cfg.SESSION}: -n tmp-<name> -c <dir> '<command>'\` (gone after a reboot).
74
+ - Docker containers you start: use \`--restart unless-stopped\` (compose: \`restart: unless-stopped\`) so they come back after a reboot.
75
+ - \`harness-device status\` shows sessions, processes and services; \`harness-device events\` shows what was restored after the last restart.
76
+ - \`sudo\` is denied. If something needs root, tell the user the exact command.`,
77
+ },
78
+
79
+ system: {
80
+ label: 'Device and disk introspection',
81
+ allow: [
82
+ 'Bash(df:*)', 'Bash(du:*)', 'Bash(free:*)', 'Bash(vm_stat:*)', 'Bash(uptime:*)', 'Bash(ps:*)', 'Bash(ss:*)', 'Bash(lsof -i:*)',
83
+ 'Bash(lsblk:*)', 'Bash(nproc:*)', 'Bash(uname:*)', 'Bash(sw_vers:*)', 'Bash(journalctl --user:*)', 'Bash(systemctl --user status:*)',
84
+ 'Bash(launchctl list:*)', 'Bash(top -bn1:*)', 'Bash(top -l 1:*)',
85
+ ],
86
+ checks: () => [],
87
+ docs: (cfg, plat) => `## Device, disk and services
88
+ - Overview: \`harness-device status\` (or the \`device_status\` / \`disk_usage\` MCP tools).
89
+ - Disk: \`df -h\`, \`du -sh <dir>\`. ${isMac(plat)
90
+ ? 'This is macOS: memory `vm_stat`, ports `lsof -iTCP -sTCP:LISTEN -n -P`, processes `top -l 1 | head -30`. Harness services are launchd agents (`launchctl list | grep harness-device`); their logs are `harness-device logs <service>`.'
91
+ : 'This is Linux: memory `free -h`, ports `ss -ltnp`, processes `ps aux --sort=-%cpu | head`. Harness services are systemd user units: `systemctl --user status \'harness-*\'`, logs `harness-device logs <service>`.'}
92
+ - Restart a stuck harness service: \`restart_service\` MCP tool (never tmux from inside a session).`,
93
+ },
94
+
95
+ display: {
96
+ label: 'Display + live viewers (Linux: virtual display + noVNC; macOS: the real screen) and a read-only tmux web view',
97
+ system: ['display'],
98
+ units: { linux: ['harness-xvfb', 'harness-vnc', 'harness-novnc', 'harness-ttyd'], darwin: ['harness-ttyd'] },
99
+ checks: async (ctx) => [
100
+ ...(isMac(ctx.platform) ? [] : [{ name: 'noVNC viewer', ok: await httpOk(`http://127.0.0.1:${ctx.cfg.NOVNC_PORT}/vnc.html`), fix: 'harness-device restart novnc' }]),
101
+ { name: 'tmux web view (ttyd)', ok: await httpOk(`http://127.0.0.1:${ctx.cfg.TTYD_PORT}/`), fix: 'harness-device restart ttyd' },
102
+ ],
103
+ docs: (cfg, plat) => isMac(plat)
104
+ ? `## Display and live viewers
105
+ This is a Mac: browsers and headed tests open on its real screen, which the user watches with macOS Screen Sharing (through \`harness-device tunnel\`). This tmux session is viewable read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`.
106
+ - Screenshot of the screen: the \`screenshot\` MCP tool, or \`screencapture -x /tmp/screen.png\`.`
107
+ : `## Display and live viewers
108
+ A virtual display \`:${cfg.DISPLAY_NUM}\` is always on (\`DISPLAY\` is already set). The user watches it at noVNC \`http://127.0.0.1:${cfg.NOVNC_PORT}/vnc.html\` and this tmux session read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`, over an SSH tunnel (\`harness-device tunnel\`) or ngrok (\`harness-device ngrok up viewers\`).
109
+ - Anything headed you start (browsers, Electron, Playwright \`--headed\`) appears there, so the user can see progress.
110
+ - Screenshot of the whole display: the \`screenshot\` MCP tool, or \`import -display :${cfg.DISPLAY_NUM} -window root /tmp/screen.png\`.`,
111
+ },
112
+
113
+ browser: {
114
+ label: 'Persistent Chromium (CDP on 127.0.0.1), logins and tabs kept across restarts',
115
+ requires: ['display'],
116
+ system: ['playwright-deps'],
117
+ units: { linux: ['harness-chromium'], darwin: ['harness-chromium'] },
118
+ userInstall: () => [['npx', ['-y', 'playwright@latest', 'install', 'chromium']]],
119
+ checks: async (ctx) => {
120
+ const v = await httpJson(`http://127.0.0.1:${ctx.cfg.CDP_PORT}/json/version`);
121
+ return [{ name: 'Chromium CDP', ok: !!v, msg: v ? v.Browser : undefined, fix: 'harness-device restart chromium' }];
122
+ },
123
+ docs: (cfg) => `## Browser
124
+ One Chromium runs on the display with a persistent profile: logins, cookies and open tabs survive reboots. Its DevTools endpoint is \`http://127.0.0.1:${cfg.CDP_PORT}\`. Prefer the Playwright MCP tools, which drive this same browser, so the user sees what you do. If it hangs: the \`browser_restart\` MCP tool.`,
125
+ },
126
+
127
+ playwright: {
128
+ label: 'Playwright MCP (attached to the device browser) + live test runs',
129
+ requires: ['browser'],
130
+ allow: ['mcp__playwright__*', 'Bash(hd-pw-live:*)', 'Bash(npx playwright:*)'],
131
+ mcp: (cfg) => [{ name: 'playwright', command: 'npx', args: ['-y', PLAYWRIGHT_MCP, '--cdp-endpoint', `http://127.0.0.1:${cfg.CDP_PORT}`] }],
132
+ checks: () => [],
133
+ docs: (cfg) => `## Playwright and tests
134
+ - Browser automation: the \`playwright\` MCP tools (already attached to the device Chromium).
135
+ - Run a project's tests so the user can watch: \`hd-pw-live run <project-dir> [playwright args]\`. It runs headed, streams output to you, and appends to \`~/.harness-device/logs/tests.log\` (\`hd-pw-live log\` to follow). Or the \`run_tests_live\` MCP tool.
136
+ - Interactive Playwright UI for the user: \`hd-pw-live ui <project-dir>\`, served on \`http://127.0.0.1:${cfg.PW_UI_PORT}\`; stop with \`hd-pw-live stop\`.`,
137
+ },
138
+
139
+ sqlite: {
140
+ label: 'SQLite CLI',
141
+ system: ['sqlite'],
142
+ allow: ['Bash(sqlite3:*)'],
143
+ checks: (ctx) => [{ name: 'sqlite3', ok: !!which('sqlite3', ctx.env), fix: 'harness-device install' }],
144
+ docs: () => `## SQLite
145
+ \`sqlite3\` is installed. Inspect with \`sqlite3 -readonly <db> '.tables'\` and \`sqlite3 -readonly -header -column <db> '<query>'\`; drop \`-readonly\` only for intended writes.`,
146
+ },
147
+
148
+ docker: {
149
+ label: 'Docker (Linux: Docker Engine; macOS: Docker Desktop if installed, else colima)',
150
+ system: ['docker'],
151
+ allow: ['Bash(docker:*)', 'Bash(colima status:*)'],
152
+ checks: (ctx) => [
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) ? (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
+ ],
156
+ docs: (cfg, plat) => `## Docker
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
+ },
159
+
160
+ dokploy: {
161
+ 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] }],
163
+ secrets: ['DOKPLOY_API_KEY'],
164
+ checks: async (ctx) => {
165
+ const url = ctx.cfg.DOKPLOY_URL;
166
+ const key = ctx.secrets.DOKPLOY_API_KEY;
167
+ const out = [
168
+ { name: 'DOKPLOY_URL set', ok: !!url, msg: url || undefined, fix: 'harness-device init --dokploy-url https://your-dokploy.example.com' },
169
+ { name: 'DOKPLOY_API_KEY secret', ok: !!key, fix: 'Dokploy → Settings → Profile → API/CLI → generate a key, then: harness-device secrets set DOKPLOY_API_KEY' },
170
+ ];
171
+ if (url && key) {
172
+ const st = await dokployApi(url, key);
173
+ out.push({ name: 'Dokploy API accepts the key', ok: st === 200, msg: st ? `HTTP ${st}` : 'unreachable', fix: st === 401 || st === 403 ? 'the key was refused: create a new one and run harness-device secrets set DOKPLOY_API_KEY' : `check that ${url} is reachable from this device` });
174
+ }
175
+ return out;
176
+ },
177
+ docs: (cfg) => `## Dokploy
178
+ Deployments go through the user's Dokploy at ${cfg.DOKPLOY_URL || '(DOKPLOY_URL not set yet)'}; nothing of Dokploy runs on this device. Use the \`dokploy\` MCP tools to inspect and deploy projects, applications, databases and compose stacks. Deploys, redeploys, deletes and env changes need the user's approval: say what you will change first.`,
179
+ },
180
+
181
+ graphify: {
182
+ label: 'graphify code knowledge graph (@dreamtree-org/graphify)',
183
+ userInstall: (ctx) => [['npm', ['install', '--prefix', ctx.paths.pkg, '--no-fund', '--no-audit', '@dreamtree-org/graphify@latest']]],
184
+ links: ['graphify', 'graphify-mcp'],
185
+ allow: ['Bash(graphify:*)', 'mcp__graphify__*'],
186
+ checks: (ctx) => [{ name: 'graphify', ok: fs.existsSync(path.join(ctx.paths.bin, 'graphify')), fix: 'harness-device install' }],
187
+ docs: () => `## graphify
188
+ \`graphify\` is installed. In a project without \`graphify-out/graph.json\`, run \`graphify .\` once: it builds the graph and wires the project's \`.mcp.json\` and Claude hooks, so later sessions use the \`graphify\` MCP tools for search and blast-radius before reading files. \`graphify doctor\` checks freshness.`,
189
+ },
190
+
191
+ ngrok: {
192
+ label: 'ngrok tunnels (off until `harness-device ngrok up`)',
193
+ system: ['ngrok'],
194
+ checks: (ctx) => [
195
+ { name: 'ngrok', ok: !!which('ngrok', ctx.env), fix: 'harness-device install' },
196
+ { name: 'ngrok authtoken', ok: fs.existsSync(ctx.paths.ngrokToken), warn: true, fix: 'harness-device ngrok token' },
197
+ ],
198
+ docs: () => `## ngrok
199
+ Public URLs are off by default. Only the user turns them on (\`harness-device ngrok up viewers|apps\`); you may read them with \`harness-device ngrok status\` and share them, but don't open new tunnels yourself.`,
200
+ },
201
+
202
+ ollama: {
203
+ label: 'Ollama local models (127.0.0.1:11434)',
204
+ system: ['ollama'],
205
+ allow: ['Bash(ollama list:*)', 'Bash(ollama ps:*)', 'Bash(ollama run:*)'],
206
+ userInstall: (ctx) =>
207
+ String(ctx.cfg.OLLAMA_MODELS || '').split(',').map((m) => m.trim()).filter(Boolean).map((m) => ['ollama', ['pull', m]]),
208
+ checks: async (ctx) => [{ name: 'Ollama API', ok: await httpOk('http://127.0.0.1:11434/api/tags'), fix: isMac(ctx.platform) ? 'brew services restart ollama' : 'sudo systemctl restart ollama' }],
209
+ docs: (cfg) => `## Local models (Ollama)
210
+ Ollama serves \`http://127.0.0.1:11434\` (OpenAI-compatible at \`/v1\`). Models: ${cfg.OLLAMA_MODELS || 'see `ollama list`'}.`,
211
+ },
212
+ };
213
+
214
+ export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'ollama'];
215
+
216
+ /** Resolve the enabled set: config list + required + dependencies, in a stable order. */
217
+ export function resolveCapabilities(ids) {
218
+ const want = new Set(ids);
219
+ for (const [id, c] of Object.entries(CAPABILITIES)) if (c.required) want.add(id);
220
+ const unknown = [...want].filter((id) => !CAPABILITIES[id]);
221
+ if (unknown.length) throw new Error(`Unknown capabilit${unknown.length > 1 ? 'ies' : 'y'}: ${unknown.join(', ')} (known: ${ORDER.join(', ')})`);
222
+ let grew = true;
223
+ while (grew) {
224
+ grew = false;
225
+ for (const id of [...want]) for (const r of CAPABILITIES[id].requires || []) if (!want.has(r)) { want.add(r); grew = true; }
226
+ }
227
+ return ORDER.filter((id) => want.has(id)).map((id) => ({ id, ...CAPABILITIES[id] }));
228
+ }
229
+
230
+ /** Logical services for a platform; heal is always there. */
231
+ export function unitsFor(caps, platformId) {
232
+ return [...caps.flatMap((c) => (c.units && c.units[platformId]) || []), 'harness-heal'];
233
+ }
234
+
235
+ export function systemStepsFor(caps) {
236
+ return [...new Set(caps.flatMap((c) => c.system || []))];
237
+ }