@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,230 @@
1
+ // macOS: launchd LaunchAgents in the user's GUI domain. They start when the
2
+ // user logs in, so an unattended reboot needs automatic login (doctor checks).
3
+ // Agents, not daemons: Claude Code keeps its login in the login Keychain,
4
+ // which is only unlocked inside the user's session.
5
+ // System packages come from Homebrew (Apple silicon) or conda-forge via pixi (Intel), as the user.
6
+
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { PKG_ROOT, run, capture, ok, which, writeFile, color } from '../util.js';
11
+
12
+ export const id = 'darwin';
13
+ export const label = 'macOS (launchd LaunchAgents)';
14
+ export const LABEL_PREFIX = 'org.dreamtree.harness-device.';
15
+
16
+ const uid = () => (typeof process.getuid === 'function' ? process.getuid() : 501);
17
+ const domain = () => `gui/${uid()}`;
18
+ export const labelOf = (u) => LABEL_PREFIX + u.replace(/^harness-/, '');
19
+ const plistName = (u) => `${labelOf(u)}.plist`;
20
+
21
+ export function serviceDir(env) {
22
+ return path.join(env.HOME || os.homedir(), 'Library', 'LaunchAgents');
23
+ }
24
+
25
+ export const userEnv = (env) => ({ ...env });
26
+
27
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
28
+
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, abandon = false }) {
31
+ return `<?xml version="1.0" encoding="UTF-8"?>
32
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33
+ <plist version="1.0">
34
+ <dict>
35
+ <key>Label</key><string>${esc(l)}</string>
36
+ <key>ProgramArguments</key>
37
+ <array>
38
+ ${args.map((a) => ` <string>${esc(a)}</string>`).join('\n')}
39
+ </array>
40
+ <key>RunAtLoad</key><true/>
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
+ ${abandon ? ' <key>AbandonProcessGroup</key><true/>\n' : ''} <key>StandardOutPath</key><string>${esc(logFile)}</string>
43
+ <key>StandardErrorPath</key><string>${esc(logFile)}</string>
44
+ </dict>
45
+ </plist>
46
+ `;
47
+ }
48
+
49
+ function intervalSeconds(s) {
50
+ const m = /^(\d+)\s*(s|sec|min|m|h)?$/.exec(String(s).trim());
51
+ if (!m) return 120;
52
+ const n = Number(m[1]);
53
+ return m[2] && m[2].startsWith('m') ? n * 60 : m[2] === 'h' ? n * 3600 : n;
54
+ }
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
+
72
+ /** The job definition of each logical unit. */
73
+ export function jobs(ctx, detect = true) {
74
+ const b = (f) => path.join(ctx.paths.bin, f);
75
+ const logFile = (u) => path.join(ctx.paths.logs, `svc-${u.replace(/^harness-/, '')}.log`);
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`;
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));
84
+ const def = {
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')] },
91
+ };
92
+ return (u) => {
93
+ const d = def[u];
94
+ if (!d) throw new Error(`${u} has no macOS service`);
95
+ return { label: labelOf(u), logFile: logFile(u), ...d };
96
+ };
97
+ }
98
+
99
+ /** filename → plist for every unit this device needs (ngrok is added by `ngrok up`). */
100
+ export function renderServices(ctx, detect = true) {
101
+ const job = jobs(ctx, detect);
102
+ const out = {};
103
+ for (const u of ctx.units) out[plistName(u)] = plist(job(u));
104
+ return out;
105
+ }
106
+
107
+ const lc = (args, opts = {}) => run('launchctl', args, { allowFail: true, ...opts });
108
+ const loaded = (l) => ok('launchctl', ['print', `${domain()}/${l}`]);
109
+
110
+ export function activate(ctx, files, { dryRun }) {
111
+ writeLaunchers(ctx, { dryRun });
112
+ const dir = serviceDir(ctx.env);
113
+ const ours = (f) => f.startsWith(LABEL_PREFIX) && f.endsWith('.plist');
114
+ const keep = new Set(Object.keys(files));
115
+ // ngrok is opened by `ngrok up`, not install: keep it while the capability is on.
116
+ if (ctx.caps.some((c) => c.id === 'ngrok') && fs.existsSync(path.join(dir, plistName('harness-ngrok')))) keep.add(plistName('harness-ngrok'));
117
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => ours(f) && !keep.has(f)) : []) {
118
+ lc(['bootout', `${domain()}/${f.slice(0, -6)}`], { dryRun });
119
+ if (!dryRun) fs.rmSync(path.join(dir, f), { force: true });
120
+ console.log(color.dim(` removed ${f} (capability turned off)`));
121
+ }
122
+ for (const [name, content] of Object.entries(files)) {
123
+ const file = path.join(dir, name);
124
+ const l = name.slice(0, -6);
125
+ const changed = !fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== content;
126
+ writeFile(file, content, { dryRun });
127
+ const isLoaded = !dryRun && loaded(l);
128
+ // Never reload the tmux job while it runs: the sessions live under it.
129
+ if (isLoaded && (l === labelOf('harness-tmux') || !changed)) continue;
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);
148
+ }
149
+ console.log(color.yellow(` ! could not load ${l}; the heal job retries it (or: launchctl bootstrap ${domain()} ${file})`));
150
+ }
151
+
152
+ export function deactivate(ctx, { dryRun }) {
153
+ const dir = serviceDir(ctx.env);
154
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.startsWith(LABEL_PREFIX)) : []) {
155
+ lc(['bootout', `${domain()}/${f.replace(/\.plist$/, '')}`], { dryRun });
156
+ dryRun ? console.log(color.dim(` rm ${f}`)) : fs.rmSync(path.join(dir, f), { force: true });
157
+ }
158
+ // The tmux server outlives its supervisor job by design; end it explicitly.
159
+ run('tmux', ['kill-session', '-t', `=${ctx.cfg.SESSION}`], { dryRun, allowFail: true, env: ctx.env });
160
+ }
161
+
162
+ export function state(ctx, u) {
163
+ const out = capture('launchctl', ['print', `${domain()}/${labelOf(u)}`]);
164
+ if (!out) return 'not loaded';
165
+ if (/^\s*state = running/m.test(out)) return 'active';
166
+ return u === 'harness-heal' ? 'active' : 'inactive'; // heal is an interval job: idle between runs
167
+ }
168
+
169
+ export function restart(ctx, u) {
170
+ return ok('launchctl', ['kickstart', '-k', `${domain()}/${labelOf(u)}`], { timeout: 60000 });
171
+ }
172
+
173
+ export function serviceLogs(ctx, u, n) {
174
+ const f = path.join(ctx.paths.logs, `svc-${u.replace(/^harness-/, '')}.log`);
175
+ return fs.existsSync(f) ? capture('tail', ['-n', String(n), f]) : `(no log yet: ${f})`;
176
+ }
177
+
178
+ export function followLogsCmd(u, ctx) {
179
+ return ['tail', ['-n', '100', '-F', path.join(ctx.paths.logs, `svc-${u.replace(/^harness-/, '')}.log`)]];
180
+ }
181
+
182
+ export function ngrokUp(ctx) {
183
+ const file = path.join(serviceDir(ctx.env), plistName('harness-ngrok'));
184
+ writeFile(file, plist(jobs(ctx)('harness-ngrok')));
185
+ lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
186
+ lc(['bootstrap', domain(), file]);
187
+ }
188
+
189
+ export function ngrokDown(ctx) {
190
+ lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
191
+ fs.rmSync(path.join(serviceDir(ctx.env), plistName('harness-ngrok')), { force: true });
192
+ }
193
+
194
+ /** System packages: Homebrew, else pixi (conda-forge), as the user. */
195
+ export function systemSetup(ctx, steps, { dryRun }) {
196
+ console.log(`${color.cyan('›')} System setup (Homebrew or pixi): ${steps.join(', ')}`);
197
+ run('bash', [path.join(PKG_ROOT, 'sh', 'setup', 'darwin.sh'), '--steps', steps.join(',')], { dryRun, env: ctx.env });
198
+ }
199
+
200
+ export function bootCheck(ctx) {
201
+ const user = ctx.env.USER || os.userInfo().username;
202
+ const auto = capture('defaults', ['read', '/Library/Preferences/com.apple.loginwindow', 'autoLoginUser']);
203
+ return [
204
+ {
205
+ name: 'automatic login (services start after an unattended reboot)',
206
+ ok: auto === user,
207
+ warn: true,
208
+ fix: 'System Settings → Users & Groups → Automatically log in as ' + user + ' (unavailable while FileVault is on). Without it, everything resumes as soon as you log in.',
209
+ },
210
+ { name: 'LaunchAgents loaded', ok: loaded(labelOf('harness-tmux')), fix: 'harness-device install' },
211
+ ];
212
+ }
213
+
214
+ export function screenshotCmd(ctx, file) {
215
+ return ['screencapture', ['-x', file]];
216
+ }
217
+
218
+ export function memory() {
219
+ const bytes = Number(capture('sysctl', ['-n', 'hw.memsize'])) || 0;
220
+ return `total ${(bytes / 2 ** 30).toFixed(1)} GiB\n` + capture('vm_stat');
221
+ }
222
+
223
+ export function viewers(cfg) {
224
+ return {
225
+ display: 'vnc://127.0.0.1:5900 (macOS Screen Sharing: System Settings → General → Sharing → Screen Sharing)',
226
+ tmux: `http://127.0.0.1:${cfg.TTYD_PORT}/`,
227
+ playwrightUi: `http://127.0.0.1:${cfg.PW_UI_PORT}/`,
228
+ tunnelPorts: [5900, cfg.TTYD_PORT, cfg.PW_UI_PORT],
229
+ };
230
+ }
@@ -0,0 +1,12 @@
1
+ import * as linux from './linux.js';
2
+ import * as darwin from './darwin.js';
3
+
4
+ export const PLATFORMS = { linux, darwin };
5
+
6
+ /** This machine's platform. HARNESS_DEVICE_PLATFORM overrides it (tests, previews). */
7
+ export function platform(env = process.env) {
8
+ const id = env.HARNESS_DEVICE_PLATFORM || process.platform;
9
+ const p = PLATFORMS[id];
10
+ if (!p) throw new Error(`harness-device runs on Linux and macOS, not ${id}.`);
11
+ return p;
12
+ }
@@ -0,0 +1,142 @@
1
+ // Linux: systemd *user* units, started at boot by linger (no login needed).
2
+ // System packages come from apt, through one sudo call.
3
+
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { PKG_ROOT, run, capture, ok, which, render, writeFile, color } from '../util.js';
8
+
9
+ export const id = 'linux';
10
+ export const label = 'Linux (systemd user services)';
11
+ const TEMPLATES = path.join(PKG_ROOT, 'templates', 'systemd');
12
+
13
+ /** Logical unit (harness-tmux, harness-heal, ...) → systemd unit name. */
14
+ export const unitName = (u) => (u === 'harness-heal' ? 'harness-heal.timer' : `${u}.service`);
15
+
16
+ export function serviceDir(env) {
17
+ return path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'), 'systemd', 'user');
18
+ }
19
+
20
+ /** systemctl --user needs the user bus; over sudo/su/cron XDG_RUNTIME_DIR may be unset. */
21
+ export function userEnv(env) {
22
+ const e = { ...env };
23
+ if (!e.XDG_RUNTIME_DIR && typeof process.getuid === 'function') e.XDG_RUNTIME_DIR = `/run/user/${process.getuid()}`;
24
+ return e;
25
+ }
26
+
27
+ export function unitVars(ctx, detect = true) {
28
+ return {
29
+ ...ctx.cfg,
30
+ HD_HOME: ctx.paths.home,
31
+ NOVNC_WEB: (detect && ['/usr/share/novnc', '/usr/share/webapps/novnc', '/opt/novnc'].find((d) => fs.existsSync(path.join(d, 'vnc.html')))) || '/usr/share/novnc',
32
+ TTYD_BIN: (detect && which('ttyd', ctx.env)) || '/usr/bin/ttyd',
33
+ CAPABILITIES: ctx.caps.map((c) => c.id).join(','),
34
+ WANTS: ctx.units.map(unitName).join(' '),
35
+ };
36
+ }
37
+
38
+ /** filename → content for every unit this device needs. */
39
+ export function renderServices(ctx, detect = true) {
40
+ const vars = unitVars(ctx, detect);
41
+ const names = ctx.units.map(unitName);
42
+ names.push('harness-heal.service', 'harness.target');
43
+ if (ctx.caps.some((c) => c.id === 'ngrok')) names.push('harness-ngrok.service');
44
+ const out = {};
45
+ for (const n of names) out[n] = render(fs.readFileSync(path.join(TEMPLATES, n), 'utf8'), vars, n);
46
+ return out;
47
+ }
48
+
49
+ const sysd = (args, env, opts = {}) => run('systemctl', ['--user', ...args], { env, ...opts });
50
+
51
+ /** Write units, drop stale ones, enable at boot, start; never restart tmux (live sessions). */
52
+ export function activate(ctx, files, { dryRun }) {
53
+ const env = userEnv(ctx.env);
54
+ const dir = serviceDir(env);
55
+ const stale = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^harness[.-]/.test(f) && !(f in files)) : [];
56
+ for (const f of stale) {
57
+ sysd(['disable', '--now', f], env, { dryRun, allowFail: true });
58
+ if (!dryRun) fs.rmSync(path.join(dir, f), { force: true });
59
+ console.log(color.dim(` removed ${f} (capability turned off)`));
60
+ }
61
+ for (const [name, content] of Object.entries(files)) writeFile(path.join(dir, name), content, { dryRun });
62
+ sysd(['daemon-reload'], env, { dryRun });
63
+ sysd(['enable', 'harness.target', 'harness-heal.timer'], env, { dryRun });
64
+ for (const u of ctx.units) {
65
+ if (u === 'harness-tmux') continue;
66
+ sysd([u === 'harness-heal' ? 'restart' : 'try-restart', unitName(u)], env, { dryRun, allowFail: true });
67
+ }
68
+ sysd(['start', 'harness.target'], env, { dryRun });
69
+ }
70
+
71
+ export function deactivate(ctx, { dryRun }) {
72
+ const env = userEnv(ctx.env);
73
+ const dir = serviceDir(env);
74
+ sysd(['disable', '--now', 'harness.target', 'harness-ngrok.service', ...ctx.units.map(unitName)], env, { dryRun, allowFail: true });
75
+ if (fs.existsSync(dir)) for (const f of fs.readdirSync(dir).filter((f) => /^harness[.-]/.test(f))) {
76
+ dryRun ? console.log(color.dim(` rm ${f}`)) : fs.rmSync(path.join(dir, f), { force: true });
77
+ }
78
+ sysd(['daemon-reload'], env, { dryRun, allowFail: true });
79
+ }
80
+
81
+ export function state(ctx, u) {
82
+ return capture('systemctl', ['--user', 'is-active', unitName(u)], { env: userEnv(ctx.env) }) || 'unknown';
83
+ }
84
+
85
+ export function restart(ctx, u) {
86
+ return ok('systemctl', ['--user', 'restart', unitName(u)], { env: userEnv(ctx.env), timeout: 60000 });
87
+ }
88
+
89
+ export function serviceLogs(ctx, u, n) {
90
+ return capture('journalctl', ['--user', '-u', unitName(u), '-n', String(n), '--no-pager'], { env: userEnv(ctx.env) }) || '(no journal entries)';
91
+ }
92
+
93
+ export function followLogsCmd(u) {
94
+ return ['journalctl', ['--user', '-f', '-u', unitName(u)]];
95
+ }
96
+
97
+ /** ngrok is a unit that exists from install but runs only after `ngrok up`. */
98
+ export function ngrokUp(ctx) {
99
+ const env = userEnv(ctx.env);
100
+ sysd(['enable', 'harness-ngrok.service'], env);
101
+ sysd(['restart', 'harness-ngrok.service'], env);
102
+ }
103
+
104
+ export function ngrokDown(ctx) {
105
+ sysd(['disable', '--now', 'harness-ngrok.service'], userEnv(ctx.env), { allowFail: true });
106
+ }
107
+
108
+ /** System packages: apt, as root, once. */
109
+ export function systemSetup(ctx, steps, { dryRun }) {
110
+ const env = ctx.env;
111
+ const user = env.USER || os.userInfo().username;
112
+ console.log(`${color.cyan('›')} System setup (sudo): ${steps.join(', ')}`);
113
+ run('sudo', ['bash', path.join(PKG_ROOT, 'sh', 'setup', 'linux.sh'), '--user', user, '--steps', steps.join(','),
114
+ '--npx', which('npx', env) || 'npx'], { dryRun });
115
+ }
116
+
117
+ export function bootCheck(ctx) {
118
+ const env = userEnv(ctx.env);
119
+ const linger = capture('loginctl', ['show-user', env.USER || os.userInfo().username, '-p', 'Linger', '--value']);
120
+ return [
121
+ { name: 'linger (services start at boot, no login needed)', ok: linger === 'yes', fix: `sudo loginctl enable-linger ${env.USER}` },
122
+ { name: 'harness.target enabled', ok: capture('systemctl', ['--user', 'is-enabled', 'harness.target'], { env }) === 'enabled', fix: 'harness-device install' },
123
+ ];
124
+ }
125
+
126
+ export function screenshotCmd(ctx, file) {
127
+ return ['import', ['-display', `:${ctx.cfg.DISPLAY_NUM}`, '-window', 'root', file]];
128
+ }
129
+
130
+ export function memory() {
131
+ return capture('free', ['-h']);
132
+ }
133
+
134
+ /** What the user opens (through the SSH tunnel) to watch the device. */
135
+ export function viewers(cfg) {
136
+ return {
137
+ display: `http://127.0.0.1:${cfg.NOVNC_PORT}/vnc.html?autoconnect=1&resize=scale`,
138
+ tmux: `http://127.0.0.1:${cfg.TTYD_PORT}/`,
139
+ playwrightUi: `http://127.0.0.1:${cfg.PW_UI_PORT}/`,
140
+ tunnelPorts: [cfg.NOVNC_PORT, cfg.TTYD_PORT, cfg.PW_UI_PORT],
141
+ };
142
+ }
@@ -0,0 +1,224 @@
1
+ // Provider "claude": Claude Code + Remote Control.
2
+ // Serving is done by sh/bin/hd-serve-claude (`claude remote-control`); this
3
+ // module wires the device's capabilities into Claude Code at user scope:
4
+ // MCP servers, a skill, a short CLAUDE.md pointer, and the permission list.
5
+
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import { run, capture, ok, which, writeFile } from '../util.js';
10
+
11
+ const MARK_START = '<!-- harness-device:start -->';
12
+ const MARK_END = '<!-- harness-device:end -->';
13
+
14
+ export const id = 'claude';
15
+ export const label = 'Claude Code (Remote Control)';
16
+
17
+ function claudeDir(env) {
18
+ return env.CLAUDE_CONFIG_DIR || path.join(env.HOME || os.homedir(), '.claude');
19
+ }
20
+
21
+ export function files(env = process.env) {
22
+ const dir = claudeDir(env);
23
+ return {
24
+ dir,
25
+ settings: path.join(dir, 'settings.json'),
26
+ skill: path.join(dir, 'skills', 'harness-device', 'SKILL.md'),
27
+ claudeMd: path.join(dir, 'CLAUDE.md'),
28
+ };
29
+ }
30
+
31
+ /** Replace (or add) our marked block in a markdown file's text. */
32
+ export function upsertBlock(text, block) {
33
+ const wrapped = `${MARK_START}\n${block.trim()}\n${MARK_END}`;
34
+ const re = new RegExp(`${MARK_START}[\\s\\S]*?${MARK_END}`);
35
+ if (re.test(text)) return text.replace(re, wrapped);
36
+ return (text.trim() ? text.replace(/\s*$/, '\n\n') : '') + wrapped + '\n';
37
+ }
38
+
39
+ export function removeBlock(text) {
40
+ const out = text.replace(new RegExp(`\\n*${MARK_START}[\\s\\S]*?${MARK_END}\\n?`), '\n');
41
+ // Only drop the blank line our block leaves at the very top, nothing of the user's.
42
+ return text.startsWith(MARK_START) ? out.replace(/^\n/, '') : out;
43
+ }
44
+
45
+ /**
46
+ * Merge our allow/deny rules into a Claude settings object.
47
+ * `prev` is what we added last time ({allow, deny}); those are taken out
48
+ * first, so rules dropped from the device go away. Rules the user had
49
+ * themselves are never removed or recorded as ours.
50
+ * Returns { settings, added } where added is the new record to keep.
51
+ */
52
+ export function mergePermissions(settings, { allow = [], deny = [] }, prev = { allow: [], deny: [] }) {
53
+ const s = JSON.parse(JSON.stringify(settings || {}));
54
+ s.permissions = s.permissions || {};
55
+ const added = { allow: [], deny: [] };
56
+ for (const kind of ['allow', 'deny']) {
57
+ const ours = new Set(prev[kind] || []);
58
+ const cur = (s.permissions[kind] || []).filter((r) => !ours.has(r));
59
+ for (const r of kind === 'allow' ? allow : deny) {
60
+ if (!cur.includes(r)) {
61
+ cur.push(r);
62
+ added[kind].push(r);
63
+ }
64
+ }
65
+ s.permissions[kind] = cur;
66
+ }
67
+ return { settings: s, added };
68
+ }
69
+
70
+ export function unmergePermissions(settings, prev) {
71
+ const s = mergePermissions(settings, { allow: [], deny: [] }, prev).settings;
72
+ if (prev && prev.cleanupPeriodDays) {
73
+ if (prev.cleanupPeriodDays.prev == null) delete s.cleanupPeriodDays;
74
+ else s.cleanupPeriodDays = prev.cleanupPeriodDays.prev;
75
+ }
76
+ return s;
77
+ }
78
+
79
+ /** Raise cleanupPeriodDays to at least `days`; returns what to remember for uninstall. */
80
+ export function applyRetention(settings, days, prev = {}) {
81
+ const had = prev.cleanupPeriodDays; // set by an earlier install: keep its original "prev"
82
+ const cur = settings.cleanupPeriodDays;
83
+ if (had) {
84
+ settings.cleanupPeriodDays = Math.max(days, had.prev ?? 0);
85
+ return { cleanupPeriodDays: had };
86
+ }
87
+ if (cur == null || cur < days) {
88
+ settings.cleanupPeriodDays = days;
89
+ return { cleanupPeriodDays: { prev: cur ?? null } };
90
+ }
91
+ return {};
92
+ }
93
+
94
+ function readJson(file, fallback) {
95
+ try {
96
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
97
+ } catch (e) {
98
+ if (e.code === 'ENOENT') return fallback;
99
+ throw new Error(`${file} is not valid JSON; fix it by hand first (${e.message})`);
100
+ }
101
+ }
102
+
103
+ export function renderSkill({ cfg, caps, projects, platform }) {
104
+ const head = `---
105
+ name: harness-device
106
+ description: How to use this machine's harness-device capabilities (device ${cfg.DEVICE}): persistent sessions that survive reboots, registered long-running processes, the always-on browser, Playwright MCP and live headed test runs the user can watch, display viewers, Docker, Dokploy, SQLite, graphify, disk and service status. Use it whenever you start servers, run tests, drive a browser, deploy, or check the device's state.
107
+ ---
108
+
109
+ # harness-device: ${cfg.DEVICE}
110
+
111
+ This machine is a harness device: a dev environment kept running for remote agent sessions. Everything below survives reboots and is restarted automatically if it dies.
112
+
113
+ Projects on this device: ${projects.map((p) => `\`${p.name}\` (${p.dir})`).join(', ') || 'none yet'}.
114
+ Device controls are available both as the \`harness-device\` MCP tools and as the \`harness-device\` CLI.
115
+ `;
116
+ return head + '\n' + caps.map((c) => (c.docs ? c.docs(cfg, platform) : '')).filter(Boolean).join('\n\n') + '\n';
117
+ }
118
+
119
+ export function renderClaudeMd({ cfg }) {
120
+ return `## harness-device
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
+ }
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
+
130
+ // harness-device MCP tools that only read, or restart the browser. proc_add,
131
+ // proc_remove, restart_service and playwright_ui still ask: they start or stop things.
132
+ export const HARNESS_TOOLS_ALLOWED = ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs',
133
+ 'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status'].map((t) => `mcp__harness-device__${t}`);
134
+
135
+ /**
136
+ * A Read() rule for an absolute path. In Claude Code rules `/x` is relative to
137
+ * the settings file; `~/x` is under home and `//x` is absolute.
138
+ */
139
+ export function readRule(abs, home) {
140
+ const rel = path.relative(home, abs);
141
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? `Read(~/${rel})` : `Read(/${abs})`;
142
+ }
143
+
144
+ /**
145
+ * Wire everything into Claude Code. ctx: { cfg, caps, projects, paths, env, dryRun, mcpServers }
146
+ */
147
+ export function apply(ctx) {
148
+ const { env, dryRun, paths } = ctx;
149
+ const f = files(env);
150
+ const claude = which('claude', env);
151
+
152
+ const stateFile = path.join(paths.home, 'claude-permissions.json');
153
+ const prev = readJson(stateFile, { allow: [], deny: [] });
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.`);
160
+
161
+ // MCP servers, user scope, re-added so a changed command line takes effect.
162
+ // Ones this device registered before but no longer has are removed.
163
+ if (!claude && !dryRun) {
164
+ ctx.warn('claude is not installed yet; skipping MCP registration (re-run install after installing Claude Code).');
165
+ } else {
166
+ for (const name of (prev.mcp || []).filter((n) => !mcpNames.includes(n))) {
167
+ run('claude', ['mcp', 'remove', '--scope', 'user', name], { dryRun, allowFail: true, env });
168
+ }
169
+ for (const s of ctx.mcpServers.filter((x) => mcpNames.includes(x.name))) {
170
+ run('claude', ['mcp', 'remove', '--scope', 'user', s.name], { dryRun, allowFail: true, env });
171
+ run('claude', ['mcp', 'add', '--scope', 'user', s.name, '--', s.command, ...(s.args || [])], { dryRun, env });
172
+ }
173
+ }
174
+
175
+ writeFile(f.skill, renderSkill(ctx), { dryRun });
176
+
177
+ const md = fs.existsSync(f.claudeMd) ? fs.readFileSync(f.claudeMd, 'utf8') : '';
178
+ writeFile(f.claudeMd, upsertBlock(md, renderClaudeMd(ctx)), { dryRun });
179
+
180
+ const allow = [...new Set(ctx.caps.flatMap((c) => c.allow || []).concat(HARNESS_TOOLS_ALLOWED))];
181
+ const home = env.HOME || os.homedir();
182
+ const deny = [...new Set(ctx.caps.flatMap((c) => c.deny || []).concat([
183
+ readRule(path.join(paths.home, 'secrets.env'), home),
184
+ readRule(path.join(paths.home, 'ngrok*'), home),
185
+ readRule(path.join(home, '.ssh', '**'), home),
186
+ ]))];
187
+ const { settings, added } = mergePermissions(readJson(f.settings, {}), { allow, deny }, prev);
188
+ // Restores resume conversations from their transcripts, so Claude Code
189
+ // must not clean them up early (its default is 30 days).
190
+ const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
191
+ writeFile(f.settings, JSON.stringify(settings, null, 2) + '\n', { dryRun });
192
+ writeFile(stateFile, JSON.stringify({ ...added, ...keep, mcp: mcpNames }, null, 2) + '\n', { dryRun });
193
+ return { allow, deny, added };
194
+ }
195
+
196
+ export function remove(ctx) {
197
+ const { env, dryRun, paths } = ctx;
198
+ const f = files(env);
199
+ // Only what this device registered: never a server of the user's with the same name.
200
+ const registered = readJson(path.join(paths.home, 'claude-permissions.json'), {}).mcp || [];
201
+ for (const name of registered) run('claude', ['mcp', 'remove', '--scope', 'user', name], { dryRun, allowFail: true, env });
202
+ if (fs.existsSync(f.skill)) dryRun ? console.log(` rm ${f.skill}`) : fs.rmSync(path.dirname(f.skill), { recursive: true, force: true });
203
+ if (fs.existsSync(f.claudeMd)) writeFile(f.claudeMd, removeBlock(fs.readFileSync(f.claudeMd, 'utf8')), { dryRun });
204
+ const stateFile = path.join(paths.home, 'claude-permissions.json');
205
+ const prev = readJson(stateFile, { allow: [], deny: [] });
206
+ if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(unmergePermissions(readJson(f.settings, {}), prev), null, 2) + '\n', { dryRun });
207
+ if (!dryRun) fs.rmSync(stateFile, { force: true });
208
+ }
209
+
210
+ export function checks(ctx) {
211
+ const { env } = ctx;
212
+ const out = [];
213
+ const claude = which('claude', env);
214
+ out.push({ name: 'claude installed', ok: !!claude, msg: claude ? capture('claude', ['--version'], { env }) : undefined, fix: 'curl -fsSL https://claude.ai/install.sh | bash' });
215
+ // Linux keeps the login in a file; macOS in the login Keychain.
216
+ const loggedIn = ctx.platform && ctx.platform.id === 'darwin'
217
+ ? ok('security', ['find-generic-password', '-s', 'Claude Code-credentials'])
218
+ : fs.existsSync(path.join(claudeDir(env), '.credentials.json'));
219
+ out.push({ name: 'claude.ai login', ok: loggedIn, warn: true, fix: 'claude auth login (choose the claude.ai account option; Remote Control needs it)' });
220
+ for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']) {
221
+ if (env[k]) out.push({ name: `${k} unset`, ok: false, warn: true, fix: `unset ${k} in your shell profile: it makes Claude Code skip the claude.ai login that Remote Control needs (harness windows already strip it)` });
222
+ }
223
+ return out;
224
+ }