@dreamtree-org/harness-device 0.0.0-stage → 0.1.0

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 +13 -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 +31 -0
  8. package/sh/bin/hd-lib.sh +74 -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 +69 -0
  16. package/sh/bin/hd-tmux-supervise +11 -0
  17. package/sh/bin/hd-with-secrets +8 -0
  18. package/sh/setup/darwin.sh +75 -0
  19. package/sh/setup/linux.sh +118 -0
  20. package/src/capabilities.js +237 -0
  21. package/src/cli.js +382 -0
  22. package/src/config.js +239 -0
  23. package/src/context.js +54 -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 +91 -0
  28. package/src/mcp/server.js +115 -0
  29. package/src/ngrok.js +62 -0
  30. package/src/platform/darwin.js +190 -0
  31. package/src/platform/index.js +12 -0
  32. package/src/platform/linux.js +142 -0
  33. package/src/providers/claude.js +212 -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,190 @@
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, run as the user (Homebrew refuses root).
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 }) {
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
+ <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
+ /** The job definition of each logical unit. */
57
+ export function jobs(ctx, detect = true) {
58
+ const b = (f) => path.join(ctx.paths.bin, f);
59
+ 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';
62
+ const c = ctx.cfg;
63
+ 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')] },
69
+ };
70
+ return (u) => {
71
+ const d = def[u];
72
+ if (!d) throw new Error(`${u} has no macOS service`);
73
+ return { label: labelOf(u), logFile: logFile(u), ...d };
74
+ };
75
+ }
76
+
77
+ /** filename → plist for every unit this device needs (ngrok is added by `ngrok up`). */
78
+ export function renderServices(ctx, detect = true) {
79
+ const job = jobs(ctx, detect);
80
+ const out = {};
81
+ for (const u of ctx.units) out[plistName(u)] = plist(job(u));
82
+ return out;
83
+ }
84
+
85
+ const lc = (args, opts = {}) => run('launchctl', args, { allowFail: true, ...opts });
86
+ const loaded = (l) => ok('launchctl', ['print', `${domain()}/${l}`]);
87
+
88
+ export function activate(ctx, files, { dryRun }) {
89
+ const dir = serviceDir(ctx.env);
90
+ const ours = (f) => f.startsWith(LABEL_PREFIX) && f.endsWith('.plist');
91
+ const keep = new Set(Object.keys(files));
92
+ // ngrok is opened by `ngrok up`, not install: keep it while the capability is on.
93
+ if (ctx.caps.some((c) => c.id === 'ngrok') && fs.existsSync(path.join(dir, plistName('harness-ngrok')))) keep.add(plistName('harness-ngrok'));
94
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => ours(f) && !keep.has(f)) : []) {
95
+ lc(['bootout', `${domain()}/${f.slice(0, -6)}`], { dryRun });
96
+ if (!dryRun) fs.rmSync(path.join(dir, f), { force: true });
97
+ console.log(color.dim(` removed ${f} (capability turned off)`));
98
+ }
99
+ for (const [name, content] of Object.entries(files)) {
100
+ const file = path.join(dir, name);
101
+ const l = name.slice(0, -6);
102
+ const changed = !fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== content;
103
+ writeFile(file, content, { dryRun });
104
+ const isLoaded = !dryRun && loaded(l);
105
+ // Never reload the tmux job while it runs: the sessions live under it.
106
+ if (isLoaded && (l === labelOf('harness-tmux') || !changed)) continue;
107
+ if (isLoaded) lc(['bootout', `${domain()}/${l}`], { dryRun });
108
+ lc(['bootstrap', domain(), file], { dryRun });
109
+ }
110
+ }
111
+
112
+ export function deactivate(ctx, { dryRun }) {
113
+ const dir = serviceDir(ctx.env);
114
+ for (const f of fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.startsWith(LABEL_PREFIX)) : []) {
115
+ lc(['bootout', `${domain()}/${f.replace(/\.plist$/, '')}`], { dryRun });
116
+ dryRun ? console.log(color.dim(` rm ${f}`)) : fs.rmSync(path.join(dir, f), { force: true });
117
+ }
118
+ // The tmux server outlives its supervisor job by design; end it explicitly.
119
+ run('tmux', ['kill-session', '-t', `=${ctx.cfg.SESSION}`], { dryRun, allowFail: true });
120
+ }
121
+
122
+ export function state(ctx, u) {
123
+ const out = capture('launchctl', ['print', `${domain()}/${labelOf(u)}`]);
124
+ if (!out) return 'not loaded';
125
+ if (/^\s*state = running/m.test(out)) return 'active';
126
+ return u === 'harness-heal' ? 'active' : 'inactive'; // heal is an interval job: idle between runs
127
+ }
128
+
129
+ export function restart(ctx, u) {
130
+ return ok('launchctl', ['kickstart', '-k', `${domain()}/${labelOf(u)}`], { timeout: 60000 });
131
+ }
132
+
133
+ export function serviceLogs(ctx, u, n) {
134
+ const f = path.join(ctx.paths.logs, `svc-${u.replace(/^harness-/, '')}.log`);
135
+ return fs.existsSync(f) ? capture('tail', ['-n', String(n), f]) : `(no log yet: ${f})`;
136
+ }
137
+
138
+ export function followLogsCmd(u, ctx) {
139
+ return ['tail', ['-n', '100', '-F', path.join(ctx.paths.logs, `svc-${u.replace(/^harness-/, '')}.log`)]];
140
+ }
141
+
142
+ export function ngrokUp(ctx) {
143
+ const file = path.join(serviceDir(ctx.env), plistName('harness-ngrok'));
144
+ writeFile(file, plist(jobs(ctx)('harness-ngrok')));
145
+ lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
146
+ lc(['bootstrap', domain(), file]);
147
+ }
148
+
149
+ export function ngrokDown(ctx) {
150
+ lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
151
+ fs.rmSync(path.join(serviceDir(ctx.env), plistName('harness-ngrok')), { force: true });
152
+ }
153
+
154
+ /** System packages: Homebrew, as the user. */
155
+ export function systemSetup(ctx, steps, { dryRun }) {
156
+ console.log(`${color.cyan('›')} System setup (Homebrew): ${steps.join(', ')}`);
157
+ run('bash', [path.join(PKG_ROOT, 'sh', 'setup', 'darwin.sh'), '--steps', steps.join(',')], { dryRun, env: ctx.env });
158
+ }
159
+
160
+ export function bootCheck(ctx) {
161
+ const user = ctx.env.USER || os.userInfo().username;
162
+ const auto = capture('defaults', ['read', '/Library/Preferences/com.apple.loginwindow', 'autoLoginUser']);
163
+ return [
164
+ {
165
+ name: 'automatic login (services start after an unattended reboot)',
166
+ ok: auto === user,
167
+ warn: true,
168
+ 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.',
169
+ },
170
+ { name: 'LaunchAgents loaded', ok: loaded(labelOf('harness-tmux')), fix: 'harness-device install' },
171
+ ];
172
+ }
173
+
174
+ export function screenshotCmd(ctx, file) {
175
+ return ['screencapture', ['-x', file]];
176
+ }
177
+
178
+ export function memory() {
179
+ const bytes = Number(capture('sysctl', ['-n', 'hw.memsize'])) || 0;
180
+ return `total ${(bytes / 2 ** 30).toFixed(1)} GiB\n` + capture('vm_stat');
181
+ }
182
+
183
+ export function viewers(cfg) {
184
+ return {
185
+ display: 'vnc://127.0.0.1:5900 (macOS Screen Sharing: System Settings → General → Sharing → Screen Sharing)',
186
+ tmux: `http://127.0.0.1:${cfg.TTYD_PORT}/`,
187
+ playwrightUi: `http://127.0.0.1:${cfg.PW_UI_PORT}/`,
188
+ tunnelPorts: [5900, cfg.TTYD_PORT, cfg.PW_UI_PORT],
189
+ };
190
+ }
@@ -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,212 @@
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
+ // harness-device MCP tools that only read, or restart the browser. proc_add,
125
+ // proc_remove, restart_service and playwright_ui still ask: they start or stop things.
126
+ export const HARNESS_TOOLS_ALLOWED = ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs',
127
+ 'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status'].map((t) => `mcp__harness-device__${t}`);
128
+
129
+ /**
130
+ * A Read() rule for an absolute path. In Claude Code rules `/x` is relative to
131
+ * the settings file; `~/x` is under home and `//x` is absolute.
132
+ */
133
+ export function readRule(abs, home) {
134
+ const rel = path.relative(home, abs);
135
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? `Read(~/${rel})` : `Read(/${abs})`;
136
+ }
137
+
138
+ /**
139
+ * Wire everything into Claude Code. ctx: { cfg, caps, projects, paths, env, dryRun, mcpServers }
140
+ */
141
+ export function apply(ctx) {
142
+ const { env, dryRun, paths } = ctx;
143
+ const f = files(env);
144
+ const claude = which('claude', env);
145
+
146
+ const stateFile = path.join(paths.home, 'claude-permissions.json');
147
+ const prev = readJson(stateFile, { allow: [], deny: [] });
148
+ const mcpNames = ctx.mcpServers.map((s) => s.name);
149
+
150
+ // MCP servers, user scope, re-added so a changed command line takes effect.
151
+ // Ones this device registered before but no longer has are removed.
152
+ if (!claude && !dryRun) {
153
+ ctx.warn('claude is not installed yet; skipping MCP registration (re-run install after installing Claude Code).');
154
+ } else {
155
+ for (const name of (prev.mcp || []).filter((n) => !mcpNames.includes(n))) {
156
+ run('claude', ['mcp', 'remove', '--scope', 'user', name], { dryRun, allowFail: true, env });
157
+ }
158
+ for (const s of ctx.mcpServers) {
159
+ run('claude', ['mcp', 'remove', '--scope', 'user', s.name], { dryRun, allowFail: true, env });
160
+ run('claude', ['mcp', 'add', '--scope', 'user', s.name, '--', s.command, ...(s.args || [])], { dryRun, env });
161
+ }
162
+ }
163
+
164
+ writeFile(f.skill, renderSkill(ctx), { dryRun });
165
+
166
+ const md = fs.existsSync(f.claudeMd) ? fs.readFileSync(f.claudeMd, 'utf8') : '';
167
+ writeFile(f.claudeMd, upsertBlock(md, renderClaudeMd(ctx)), { dryRun });
168
+
169
+ const allow = [...new Set(ctx.caps.flatMap((c) => c.allow || []).concat(HARNESS_TOOLS_ALLOWED))];
170
+ const home = env.HOME || os.homedir();
171
+ const deny = [...new Set(ctx.caps.flatMap((c) => c.deny || []).concat([
172
+ readRule(path.join(paths.home, 'secrets.env'), home),
173
+ readRule(path.join(paths.home, 'ngrok*'), home),
174
+ readRule(path.join(home, '.ssh', '**'), home),
175
+ ]))];
176
+ const { settings, added } = mergePermissions(readJson(f.settings, {}), { allow, deny }, prev);
177
+ // Restores resume conversations from their transcripts, so Claude Code
178
+ // must not clean them up early (its default is 30 days).
179
+ const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
180
+ writeFile(f.settings, JSON.stringify(settings, null, 2) + '\n', { dryRun });
181
+ writeFile(stateFile, JSON.stringify({ ...added, ...keep, mcp: mcpNames }, null, 2) + '\n', { dryRun });
182
+ return { allow, deny, added };
183
+ }
184
+
185
+ export function remove(ctx) {
186
+ const { env, dryRun, paths } = ctx;
187
+ const f = files(env);
188
+ 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 });
190
+ if (fs.existsSync(f.skill)) dryRun ? console.log(` rm ${f.skill}`) : fs.rmSync(path.dirname(f.skill), { recursive: true, force: true });
191
+ if (fs.existsSync(f.claudeMd)) writeFile(f.claudeMd, removeBlock(fs.readFileSync(f.claudeMd, 'utf8')), { dryRun });
192
+ const stateFile = path.join(paths.home, 'claude-permissions.json');
193
+ const prev = readJson(stateFile, { allow: [], deny: [] });
194
+ if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(unmergePermissions(readJson(f.settings, {}), prev), null, 2) + '\n', { dryRun });
195
+ if (!dryRun) fs.rmSync(stateFile, { force: true });
196
+ }
197
+
198
+ export function checks(ctx) {
199
+ const { env } = ctx;
200
+ const out = [];
201
+ const claude = which('claude', env);
202
+ out.push({ name: 'claude installed', ok: !!claude, msg: claude ? capture('claude', ['--version'], { env }) : undefined, fix: 'curl -fsSL https://claude.ai/install.sh | bash' });
203
+ // Linux keeps the login in a file; macOS in the login Keychain.
204
+ const loggedIn = ctx.platform && ctx.platform.id === 'darwin'
205
+ ? ok('security', ['find-generic-password', '-s', 'Claude Code-credentials'])
206
+ : fs.existsSync(path.join(claudeDir(env), '.credentials.json'));
207
+ out.push({ name: 'claude.ai login', ok: loggedIn, warn: true, fix: 'claude auth login (choose the claude.ai account option; Remote Control needs it)' });
208
+ for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']) {
209
+ 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)` });
210
+ }
211
+ return out;
212
+ }