@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
package/src/context.js ADDED
@@ -0,0 +1,66 @@
1
+ import fs from 'node:fs';
2
+ import { loadConfig, paths, projects, capabilityIds, mcpServers, parseEnv } from './config.js';
3
+ import { resolveCapabilities, unitsFor } from './capabilities.js';
4
+ import { platform as detectPlatform } from './platform/index.js';
5
+ import * as claude from './providers/claude.js';
6
+
7
+ export const PROVIDERS = { claude };
8
+
9
+ export function provider(idName) {
10
+ const p = PROVIDERS[idName];
11
+ if (!p) throw new Error(`Provider "${idName}" is not supported yet (available: ${Object.keys(PROVIDERS).join(', ')}).`);
12
+ return p;
13
+ }
14
+
15
+ export function readSecrets(file) {
16
+ try {
17
+ return parseEnv(fs.readFileSync(file, 'utf8'));
18
+ } catch {
19
+ return {};
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Add the services' PATH (runtime.env) to the caller's, so the CLI finds the
25
+ * same tmux/ttyd the services use (e.g. ~/.pixi/bin) from any shell.
26
+ */
27
+ function withServicePath(env) {
28
+ const f = paths(env).runtimeEnv;
29
+ if (!fs.existsSync(f)) return env;
30
+ const svc = parseEnv(fs.readFileSync(f, 'utf8')).PATH || '';
31
+ const all = [...String(env.PATH || '').split(':'), ...svc.split(':')].filter(Boolean);
32
+ return { ...env, PATH: [...new Set(all)].join(':') };
33
+ }
34
+
35
+ /** Everything a command needs to know about this device. */
36
+ export function loadContext(rawEnv = process.env, { dryRun = false } = {}) {
37
+ const plat = detectPlatform(rawEnv);
38
+ const env = withServicePath(plat.userEnv(rawEnv));
39
+ const { cfg, exists } = loadConfig(env);
40
+ const caps = resolveCapabilities(capabilityIds(cfg));
41
+ return {
42
+ env,
43
+ dryRun,
44
+ exists,
45
+ cfg,
46
+ platform: plat,
47
+ paths: { ...paths(env), units: plat.serviceDir(env) },
48
+ caps,
49
+ units: unitsFor(caps, plat.id),
50
+ projects: projects(cfg),
51
+ secrets: readSecrets(paths(env).secrets),
52
+ provider: provider(cfg.PROVIDER),
53
+ warn: (m) => console.log(`! ${m}`),
54
+ };
55
+ }
56
+
57
+ /** The MCP servers the provider registers: each capability's, the device's own, and MCP_* from config. */
58
+ export function allMcpServers(ctx) {
59
+ const list = ctx.caps.flatMap((c) => (c.mcp ? c.mcp(ctx.cfg, ctx.paths) : []));
60
+ list.push({ name: 'harness-device', command: `${ctx.paths.bin}/harness-device`, args: ['mcp'] });
61
+ for (const s of mcpServers(ctx.cfg)) {
62
+ const [command, ...args] = s.command.split(/\s+/).filter(Boolean);
63
+ list.push({ name: s.name, command: `${ctx.paths.bin}/hd-with-secrets`, args: [command, ...args] });
64
+ }
65
+ return list;
66
+ }
package/src/device.js ADDED
@@ -0,0 +1,127 @@
1
+ // Device operations shared by the CLI and the harness-device MCP server.
2
+ // Everything OS-specific goes through ctx.platform (src/platform/*).
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { spawn } from 'node:child_process';
7
+ import { capture, ok, httpJson, which } from './util.js';
8
+ import { listSessions, listProcs, recentEvents } from './state.js';
9
+
10
+ const short = (u) => u.replace(/^harness-/, '');
11
+ const logical = (name) => (name.startsWith('harness-') ? name : `harness-${name}`).replace(/\.(service|timer)$/, '');
12
+
13
+ export function serviceStates(ctx) {
14
+ return ctx.units.map((unit) => ({ unit, state: ctx.platform.state(ctx, unit) }));
15
+ }
16
+
17
+ export function viewers(cfg, plat) {
18
+ const v = plat.viewers(cfg);
19
+ return { display: v.display, tmux: v.tmux, playwrightUi: v.playwrightUi, cdp: `http://127.0.0.1:${cfg.CDP_PORT}/json/version` };
20
+ }
21
+
22
+ export function tunnelCommand(cfg, plat, host = '<user>@<this-machine>') {
23
+ return `ssh -N ${plat.viewers(cfg).tunnelPorts.map((p) => `-L ${p}:127.0.0.1:${p}`).join(' ')} ${host}`;
24
+ }
25
+
26
+ export function diskUsage(ctx) {
27
+ const df = capture('df', ['-h', '/', ctx.env.HOME || '/']);
28
+ const dirs = [ctx.paths.home, ...ctx.projects.map((p) => p.dir)].filter((d) => fs.existsSync(d));
29
+ const du = dirs.length ? capture('du', ['-sh', ...dirs], { timeout: 30000 }) : '';
30
+ return { df, du, memory: ctx.platform.memory(), load: capture('uptime') };
31
+ }
32
+
33
+ export function dockerSummary(ctx) {
34
+ if (!which('docker', ctx && ctx.env)) return { installed: false };
35
+ const ps = capture('docker', ['ps', '-a', '--format', '{{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'], { env: ctx.env });
36
+ const df = capture('docker', ['system', 'df'], { env: ctx.env });
37
+ return { installed: true, reachable: ok('docker', ['info'], { timeout: 20000, env: ctx.env }), containers: ps, df };
38
+ }
39
+
40
+ export async function status(ctx) {
41
+ const cdp = await httpJson(`http://127.0.0.1:${ctx.cfg.CDP_PORT}/json/version`, 2000);
42
+ return {
43
+ device: ctx.cfg.DEVICE,
44
+ platform: ctx.platform.id,
45
+ provider: ctx.cfg.PROVIDER,
46
+ capabilities: ctx.caps.map((c) => c.id),
47
+ serveMode: ctx.cfg.SERVE_MODE,
48
+ sessions: listSessions(ctx),
49
+ procs: listProcs(ctx),
50
+ events: recentEvents(ctx, 10),
51
+ services: serviceStates(ctx),
52
+ browser: cdp ? cdp.Browser : null,
53
+ viewers: viewers(ctx.cfg, ctx.platform),
54
+ load: capture('uptime'),
55
+ disk: capture('df', ['-h', '/']),
56
+ };
57
+ }
58
+
59
+ /** Log of a project / session window / process window / test runs / harness service. */
60
+ export function logs(ctx, target, lines = 100) {
61
+ const n = Math.max(1, Math.min(2000, Number(lines) || 100));
62
+ const proj = ctx.projects.find((p) => p.name === target);
63
+ if (proj || target === 'tests' || /^(rc|proc)-[A-Za-z0-9_-]+$/.test(target)) {
64
+ const file = path.join(ctx.paths.logs, proj ? `rc-${proj.name}.log` : `${target}.log`);
65
+ return fs.existsSync(file) ? capture('tail', ['-n', String(n), file]) : `(no log yet: ${file})`;
66
+ }
67
+ const u = logical(target);
68
+ if (!ctx.units.includes(u) && u !== 'harness-ngrok') throw new Error(`Unknown log target "${target}" (projects, rc-…, proc-…, tests, or services: ${ctx.units.map(short).join(', ')})`);
69
+ return ctx.platform.serviceLogs(ctx, u, n);
70
+ }
71
+
72
+ /** True for any spelling of the tmux service (tmux, harness-tmux, tmux.service, ...). */
73
+ export const isTmux = (name) => logical(String(name)) === 'harness-tmux';
74
+
75
+ export function restartService(ctx, name, { allowTmux = false } = {}) {
76
+ const u = logical(name);
77
+ if (u === 'harness-tmux' && !allowTmux) throw new Error('Restarting tmux ends every Remote Control session on the device, including this one; refused. The user can run it from a shell outside tmux: harness-device restart tmux');
78
+ if (!ctx.units.includes(u)) throw new Error(`Not a service of this device: ${short(u)} (services: ${ctx.units.map(short).join(', ')})`);
79
+ const restarted = ctx.platform.restart(ctx, u);
80
+ return { service: short(u), restarted, state: ctx.platform.state(ctx, u) };
81
+ }
82
+
83
+ /** PNG of the display (Linux: the virtual display; macOS: the screen), as base64. */
84
+ export function screenshot(ctx) {
85
+ const file = path.join(ctx.paths.logs, 'screenshot.png');
86
+ const [cmd, args] = ctx.platform.screenshotCmd(ctx, file);
87
+ if (!ok(cmd, args, { timeout: 20000 }) || !fs.existsSync(file)) {
88
+ throw new Error(ctx.platform.id === 'darwin'
89
+ ? 'screenshot failed: give the terminal / tmux Screen Recording permission (System Settings → Privacy & Security)'
90
+ : 'screenshot failed (is the display capability on and ImageMagick installed?)');
91
+ }
92
+ return fs.readFileSync(file).toString('base64');
93
+ }
94
+
95
+ /** Run hd-pw-live with a time limit; returns the exit code and the tail of the output. */
96
+ export function runTestsLive(ctx, dir, args = [], timeoutMs = 15 * 60 * 1000) {
97
+ return new Promise((resolve) => {
98
+ const child = spawn(path.join(ctx.paths.bin, 'hd-pw-live'), ['run', dir, ...args], { env: ctx.env });
99
+ let out = '';
100
+ const keep = (d) => {
101
+ out += d;
102
+ if (out.length > 200000) out = out.slice(-100000);
103
+ };
104
+ child.stdout.on('data', keep);
105
+ child.stderr.on('data', keep);
106
+ const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
107
+ child.on('close', (code, signal) => {
108
+ clearTimeout(timer);
109
+ resolve({ code, signal, output: out.slice(-30000) });
110
+ });
111
+ child.on('error', (e) => {
112
+ clearTimeout(timer);
113
+ resolve({ code: -1, output: String(e.message) });
114
+ });
115
+ });
116
+ }
117
+
118
+ export function pwUi(ctx, dir, stop = false) {
119
+ const bin = path.join(ctx.paths.bin, 'hd-pw-live');
120
+ return stop ? capture(bin, ['stop'], { env: ctx.env }) : capture(bin, ['ui', dir], { env: ctx.env });
121
+ }
122
+
123
+ export async function ngrokStatus() {
124
+ const j = await httpJson('http://127.0.0.1:4040/api/tunnels', 2000);
125
+ if (!j) return { running: false, tunnels: [] };
126
+ return { running: true, tunnels: (j.tunnels || []).map((t) => ({ name: t.name, url: t.public_url, addr: t.config && t.config.addr })) };
127
+ }
package/src/doctor.js ADDED
@@ -0,0 +1,40 @@
1
+ import fs from 'node:fs';
2
+ import { validateConfig } from './config.js';
3
+ import { serviceStates } from './device.js';
4
+ import { color } from './util.js';
5
+
6
+ /** Collect every check: config, core runtime, services, capabilities, provider. */
7
+ export async function collect(ctx) {
8
+ const out = [];
9
+ const errs = validateConfig(ctx.cfg, ctx.env);
10
+ out.push({ group: 'config', name: 'config.env valid', ok: ctx.exists && !errs.length, msg: errs.join('; ') || undefined, fix: ctx.exists ? `edit ${ctx.paths.config}` : 'harness-device init' });
11
+ out.push({ group: 'config', name: 'installed (runtime.env)', ok: fs.existsSync(ctx.paths.runtimeEnv), fix: 'harness-device install' });
12
+ for (const p of ctx.projects) out.push({ group: 'config', name: `project ${p.name} dir`, ok: fs.existsSync(p.dir), msg: p.dir, fix: `mkdir -p ${p.dir} or git clone into it` });
13
+ for (const r of ctx.platform.bootCheck(ctx)) out.push({ group: 'restart recovery', ...r });
14
+ for (const s of serviceStates(ctx)) {
15
+ out.push({ group: 'services', name: s.unit.replace(/^harness-/, ''), ok: s.state === 'active', msg: s.state === 'active' ? undefined : s.state, fix: `harness-device logs ${s.unit.replace(/^harness-/, '')}` });
16
+ }
17
+ for (const cap of ctx.caps) {
18
+ if (!cap.checks) continue;
19
+ for (const r of await cap.checks(ctx)) out.push({ group: cap.id, ...r });
20
+ }
21
+ for (const r of ctx.provider.checks(ctx)) out.push({ group: ctx.provider.id, ...r });
22
+ return out;
23
+ }
24
+
25
+ export function print(results) {
26
+ let group = '';
27
+ for (const r of results) {
28
+ if (r.group !== group) {
29
+ group = r.group;
30
+ console.log(color.bold(`\n${group}`));
31
+ }
32
+ const mark = r.ok ? color.green('✓') : r.warn ? color.yellow('!') : color.red('✗');
33
+ console.log(` ${mark} ${r.name}${r.msg ? color.dim(` ${r.msg}`) : ''}`);
34
+ if (!r.ok && r.fix) console.log(color.dim(` fix: ${r.fix}`));
35
+ }
36
+ const bad = results.filter((r) => !r.ok && !r.warn).length;
37
+ const warn = results.filter((r) => !r.ok && r.warn).length;
38
+ console.log(`\n${bad ? color.red(`${bad} failing`) : color.green('all required checks pass')}${warn ? color.yellow(`, ${warn} warning(s)`) : ''}`);
39
+ return bad;
40
+ }
package/src/fleet.js ADDED
@@ -0,0 +1,94 @@
1
+ // Many devices, one view. Run from a laptop (or any device): every device is
2
+ // reached over plain ssh, so there is no central server. Claude.ai already
3
+ // routes the Remote Control sessions; this only installs, checks and lists.
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { spawn, spawnSync } from 'node:child_process';
8
+ import { NAME_RE } from './config.js';
9
+ import { PKG, color } from './util.js';
10
+
11
+ export function readFleet(file) {
12
+ if (!fs.existsSync(file)) return [];
13
+ return fs.readFileSync(file, 'utf8').split('\n').map((l) => l.trim()).filter((l) => l && !l.startsWith('#'))
14
+ .map((l) => { const [name, host] = l.split(/\s+/); return { name, host }; });
15
+ }
16
+
17
+ export function writeFleet(file, list) {
18
+ fs.mkdirSync(path.dirname(file), { recursive: true });
19
+ fs.writeFileSync(file, '# name\tssh target (user@host or ~/.ssh/config alias)\n' + list.map((d) => `${d.name}\t${d.host}`).join('\n') + '\n', { mode: 0o600 });
20
+ }
21
+
22
+ export function addDevice(file, name, host) {
23
+ if (!NAME_RE.test(name)) throw new Error('Device name must be letters, digits, _ or -.');
24
+ if (!/^[A-Za-z0-9._@][A-Za-z0-9._@:-]*$/.test(host || '')) throw new Error('ssh target must look like user@host or an ssh alias.');
25
+ const list = readFleet(file).filter((d) => d.name !== name);
26
+ list.push({ name, host });
27
+ writeFleet(file, list);
28
+ }
29
+
30
+ export function removeDevice(file, name) {
31
+ const list = readFleet(file);
32
+ if (!list.some((d) => d.name === name)) throw new Error(`No device "${name}" in the fleet.`);
33
+ writeFleet(file, list.filter((d) => d.name !== name));
34
+ }
35
+
36
+ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
37
+
38
+ /** Remote shell line that runs harness-device on the device (installed copy, else npx). */
39
+ export function remoteLine(args) {
40
+ const npx = `npx -y ${PKG.name}@${PKG.version}`;
41
+ return `H="$HOME/.harness-device/bin/harness-device"; if [ -x "$H" ]; then set -- "$H"; else set -- ${npx}; fi; PATH="$HOME/.local/bin:$PATH" "$@" ${args.map(shq).join(' ')}`;
42
+ }
43
+
44
+ function sshJson(host, args, timeoutMs = 20000) {
45
+ return new Promise((resolve) => {
46
+ const child = spawn('ssh', ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=8', '--', host, `bash -lc ${shq(remoteLine(args))}`]);
47
+ let out = '';
48
+ let err = '';
49
+ child.stdout.on('data', (d) => (out += d));
50
+ child.stderr.on('data', (d) => (err += d));
51
+ const t = setTimeout(() => child.kill(), timeoutMs);
52
+ child.on('close', (code) => {
53
+ clearTimeout(t);
54
+ try {
55
+ resolve({ ok: true, data: JSON.parse(out.slice(out.indexOf('{'))) });
56
+ } catch {
57
+ resolve({ ok: false, error: (err || out || `exit ${code}`).trim().split('\n').pop() });
58
+ }
59
+ });
60
+ });
61
+ }
62
+
63
+ export async function fleetStatus(file) {
64
+ const list = readFleet(file);
65
+ if (!list.length) {
66
+ console.log('No devices yet. Add one: harness-device fleet add <name> <user@host>');
67
+ return [];
68
+ }
69
+ const res = await Promise.all(list.map(async (d) => ({ ...d, ...(await sshJson(d.host, ['status', '--json'])) })));
70
+ for (const r of res) {
71
+ if (!r.ok) {
72
+ console.log(`${color.red('✗')} ${color.bold(r.name)} ${color.dim(r.host)} ${r.error}`);
73
+ continue;
74
+ }
75
+ const s = r.data;
76
+ const svcBad = s.services.filter((x) => x.state !== 'active').map((x) => x.unit);
77
+ const projects = s.sessions.map((p) => (p.failing ? color.red(`${p.name} (failing)`) : p.running ? color.green(p.name) : color.red(`${p.name} (down)`))).join(', ') || color.dim('no projects');
78
+ console.log(`${svcBad.length ? color.yellow('!') : color.green('✓')} ${color.bold(r.name)} ${color.dim(`${r.host} · ${s.capabilities.join(',')}`)}`);
79
+ console.log(` sessions: ${projects}`);
80
+ if (svcBad.length) console.log(` ${color.yellow(`down: ${svcBad.join(', ')}`)}`);
81
+ console.log(color.dim(` ${s.load}`));
82
+ }
83
+ return res;
84
+ }
85
+
86
+ /** Interactive run on one device (tty for sudo prompts), e.g. init / install / doctor / attach. */
87
+ export function fleetRun(file, name, args) {
88
+ const d = readFleet(file).find((x) => x.name === name || x.host === name);
89
+ const host = d ? d.host : name;
90
+ // Never let a host turn into an ssh option (-oProxyCommand=...).
91
+ if (!/^[A-Za-z0-9._@][A-Za-z0-9._@:-]*$/.test(host)) throw new Error(`Not a device or ssh target: ${host}`);
92
+ const r = spawnSync('ssh', ['-t', '--', host, `bash -lc ${shq(remoteLine(args))}`], { stdio: 'inherit' });
93
+ return r.status ?? 1;
94
+ }
package/src/install.js ADDED
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { validateConfig, renderRuntimeEnv, renderProjectsTsv } from './config.js';
5
+ import { systemStepsFor } from './capabilities.js';
6
+ import { allMcpServers } from './context.js';
7
+ import { PKG, PKG_ROOT, run, writeFile, log, color } from './util.js';
8
+
9
+ function installSpec() {
10
+ // From the npm registry (npx / global install) pin the running version; from
11
+ // a source checkout install that folder.
12
+ return PKG_ROOT.split(path.sep).includes('node_modules') ? `${PKG.name}@${PKG.version}` : PKG_ROOT;
13
+ }
14
+
15
+ function link(target, linkPath, dryRun) {
16
+ if (dryRun) return console.log(color.dim(` ln -sf ${target} ${linkPath}`));
17
+ fs.mkdirSync(path.dirname(linkPath), { recursive: true });
18
+ fs.rmSync(linkPath, { force: true });
19
+ fs.symlinkSync(target, linkPath);
20
+ }
21
+
22
+ export async function install(ctx, opts = {}) {
23
+ const { dryRun, env, platform: plat } = ctx;
24
+ const p = ctx.paths;
25
+ if (!ctx.exists) throw new Error('No config yet. Run: harness-device init --project <name>:<dir>');
26
+ const errs = validateConfig(ctx.cfg, env);
27
+ if (errs.length) throw new Error(`Config problems in ${p.config}:\n - ${errs.join('\n - ')}`);
28
+ if (process.platform !== plat.id && !dryRun) throw new Error(`This config targets ${plat.id} but this machine is ${process.platform}; only --dry-run works here.`);
29
+ if (!ctx.projects.length) log.warn('No projects configured; the device will run without agent sessions (add one: harness-device project add name:/path).');
30
+ for (const pr of ctx.projects) if (!fs.existsSync(pr.dir)) log.warn(`Project ${pr.name}: ${pr.dir} does not exist yet.`);
31
+
32
+ log.step(`Installing harness-device ${PKG.version} on ${color.bold(ctx.cfg.DEVICE)} [${plat.label}]: ${ctx.caps.map((c) => c.id).join(', ')}`);
33
+
34
+ // 1. Files under ~/.harness-device. Services must not point into the npx cache.
35
+ for (const d of [p.home, p.bin, p.logs, p.profile, p.state]) if (!dryRun) fs.mkdirSync(d, { recursive: true, mode: 0o700 });
36
+ const shBin = path.join(PKG_ROOT, 'sh', 'bin');
37
+ for (const f of fs.readdirSync(shBin)) {
38
+ if (dryRun) { console.log(color.dim(` copy ${f} → ${p.bin}/`)); continue; }
39
+ // Copy, then rename over the old file: a running bash script keeps reading
40
+ // its old copy instead of new bytes at the same offset (which crashes it).
41
+ const dest = path.join(p.bin, f);
42
+ const tmp = `${dest}.new-${process.pid}`;
43
+ fs.copyFileSync(path.join(shBin, f), tmp);
44
+ fs.chmodSync(tmp, f.endsWith('.sh') ? 0o644 : 0o755);
45
+ fs.renameSync(tmp, dest);
46
+ }
47
+ writeFile(p.runtimeEnv, renderRuntimeEnv(ctx.cfg, env, { units: ctx.units, platformId: plat.id }), { mode: 0o600, dryRun });
48
+ writeFile(p.projects, renderProjectsTsv(ctx.cfg), { mode: 0o600, dryRun });
49
+ if (!fs.existsSync(p.secrets)) writeFile(p.secrets, '# KEY=value, loaded for MCP servers and other tools. Never Anthropic keys.\n', { mode: 0o600, dryRun });
50
+
51
+ // 2. System packages (Linux: apt through sudo; macOS: Homebrew or pixi, as the user).
52
+ if (!opts.skipSystem) plat.systemSetup(ctx, systemStepsFor(ctx.caps), { dryRun });
53
+
54
+ // 3. A persistent copy of this CLI (for the services, the MCP server and the agent) + user-level tools.
55
+ log.step('Installing the harness-device CLI and user-level tools');
56
+ run('npm', ['install', '--prefix', p.pkg, '--no-fund', '--no-audit', '--omit=dev', installSpec()], { dryRun, env });
57
+ for (const c of ctx.caps) for (const [cmd, args] of c.userInstall ? c.userInstall(ctx) : []) run(cmd, args, { dryRun, env });
58
+ for (const b of ['harness-device', ...ctx.caps.flatMap((c) => c.links || [])]) link(path.join(p.pkg, 'node_modules', '.bin', b), path.join(p.bin, b), dryRun);
59
+ link(path.join(p.bin, 'harness-device'), path.join(env.HOME || os.homedir(), '.local', 'bin', 'harness-device'), dryRun);
60
+
61
+ // 4. Services that start at boot (Linux) / login (macOS) and restart on failure.
62
+ log.step(`Services → ${p.units}`);
63
+ plat.activate(ctx, plat.renderServices(ctx, !dryRun), { dryRun });
64
+ run(path.join(p.bin, 'hd-heal'), [], { dryRun, env, allowFail: true });
65
+
66
+ // 5. Wire capabilities into the agent.
67
+ log.step(`Wiring capabilities into ${ctx.provider.label}`);
68
+ const servers = allMcpServers(ctx);
69
+ const res = ctx.provider.apply({ ...ctx, mcpServers: servers, warn: log.warn });
70
+ log.info(color.dim(` MCP: ${servers.map((s) => s.name).join(', ')} · pre-approved rules: ${res.allow.length} · denied: ${res.deny.length}`));
71
+
72
+ for (const c of ctx.caps) for (const k of c.secrets || []) if (!ctx.secrets[k]) log.warn(`${c.id}: set ${k} with: harness-device secrets set ${k}`);
73
+ if (ctx.caps.some((c) => c.id === 'dokploy') && !ctx.cfg.DOKPLOY_URL) log.warn('dokploy: set your Dokploy URL with: harness-device init --dokploy-url https://…');
74
+ log.ok(dryRun ? 'Dry run complete; nothing was changed.' : 'Installed.');
75
+ if (!dryRun) {
76
+ log.info(`
77
+ Next, once per device:
78
+ 1. ${color.bold('claude auth login')} choose the claude.ai account (Remote Control needs it)
79
+ 2. ${color.bold('harness-device attach')} answer the one-time "trust this folder" / "enable Remote Control" prompts
80
+ in each project window (Ctrl-b n: next window, Ctrl-b d: detach)
81
+ 3. ${color.bold('harness-device doctor')} everything should be green${plat.id === 'darwin' ? '\n (on a Mac, turn on automatic login if it must recover from reboots unattended)' : ''}
82
+ Sessions appear in the Claude app as ${ctx.projects.map((pr) => `${ctx.cfg.DEVICE}-${pr.name}`).join(', ') || '<device>-<project>'} and resume after any restart.
83
+ Watch live: ${color.bold('harness-device tunnel')}`);
84
+ }
85
+ }
86
+
87
+ export function uninstall(ctx, { purge = false } = {}) {
88
+ const { dryRun, env } = ctx;
89
+ const p = ctx.paths;
90
+ ctx.platform.deactivate(ctx, { dryRun });
91
+ ctx.provider.remove({ ...ctx, mcpServers: allMcpServers(ctx) });
92
+ if (!dryRun) fs.rmSync(path.join(env.HOME || os.homedir(), '.local', 'bin', 'harness-device'), { force: true });
93
+ if (purge && !dryRun) fs.rmSync(p.home, { recursive: true, force: true });
94
+ log.ok(purge ? `Removed services, agent wiring and ${p.home}.` : `Removed services and agent wiring. Config, session state, browser profile and logs stay in ${p.home} (--purge deletes them).`);
95
+ log.info(color.dim('System packages (Docker, ngrok, Ollama, apt/Homebrew/pixi packages) are left installed.'));
96
+ }
@@ -0,0 +1,115 @@
1
+ // `harness-device mcp`: the device's own controls as typed MCP tools.
2
+ // Same functions as the CLI (src/device.js), so both always agree.
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
+ import { z } from 'zod';
9
+ import { loadContext } from '../context.js';
10
+ import * as device from '../device.js';
11
+ import * as state from '../state.js';
12
+ import { PKG, sendChildOutputToStderr } from '../util.js';
13
+
14
+ const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
15
+ const fail = (e) => ({ isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] });
16
+
17
+ const has = (ctx, id) => ctx.caps.some((c) => c.id === id);
18
+
19
+ export function buildServer(env = process.env) {
20
+ const ctx = () => loadContext(env);
21
+ const base = ctx();
22
+ const server = new McpServer({ name: 'harness-device', version: PKG.version });
23
+ const tool = (name, description, inputSchema, fn) =>
24
+ server.registerTool(name, { description, inputSchema }, async (args) => {
25
+ try {
26
+ return await fn(ctx(), args || {});
27
+ } catch (e) {
28
+ return fail(e);
29
+ }
30
+ });
31
+
32
+ tool('device_status', `Status of device ${base.cfg.DEVICE}: projects and their Remote Control sessions, harness services, browser, viewers, load and disk.`, {},
33
+ async (c) => text(await device.status(c)));
34
+
35
+ tool('sessions', 'Persistent agent sessions on this device: each project slot, its pinned conversation id, whether it is running, last activity, and failures. These survive reboots.', {},
36
+ async (c) => text({ serveMode: c.cfg.SERVE_MODE, sessions: state.listSessions(c), events: state.recentEvents(c, 15) }));
37
+
38
+ tool('proc_list', 'Registered long-running processes (dev servers, watchers, workers) that are kept alive and restored after reboots.', {},
39
+ async (c) => text(state.listProcs(c)));
40
+
41
+ tool('proc_add', 'Register a long-running process so it keeps running across crashes and reboots, in tmux window proc-<name>. Use this instead of running servers in the foreground. Re-adding a name replaces it.',
42
+ { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), dir: z.string().describe('absolute working directory'), command: z.string().describe('one shell line, e.g. "npm run dev -- --port 5173"') },
43
+ async (c, a) => {
44
+ state.addProc(c, a.name, a.dir, a.command);
45
+ return text(`proc ${a.name} registered; window proc-${a.name}; logs: logs tool with target "proc-${a.name}"`);
46
+ });
47
+
48
+ tool('proc_remove', 'Stop and unregister a long-running process.', { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/) },
49
+ async (c, a) => { state.removeProc(c, a.name); return text(`proc ${a.name} removed`); });
50
+
51
+ tool('viewers', 'URLs where the user watches live progress (noVNC display, read-only tmux, Playwright UI) and the SSH tunnel command to reach them.', {},
52
+ async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
53
+
54
+ tool('disk_usage', 'Disk (df), sizes of the harness home and every project folder (du), memory and load.', {},
55
+ async (c) => text(device.diskUsage(c)));
56
+
57
+ tool('logs', 'Recent log lines: a project name or window (rc-<project>[-n], proc-<name>), "tests" (live test runs), or a harness service such as chromium, tmux, xvfb, novnc, ttyd, heal, ngrok.',
58
+ { target: z.string().describe('project name, "tests", or service name'), lines: z.number().int().min(1).max(2000).optional() },
59
+ async (c, a) => text(device.logs(c, a.target, a.lines)));
60
+
61
+ tool('restart_service', 'Restart one harness service (e.g. chromium, ttyd, novnc on Linux). Restarting "tmux" ends every Remote Control session on the device, including this one, so it is refused.',
62
+ { service: z.string() },
63
+ async (c, a) => {
64
+ return text(device.restartService(c, a.service));
65
+ });
66
+
67
+ if (has(base, 'browser')) {
68
+ tool('browser_restart', 'Restart the device Chromium (profile, logins and cookies are kept). Use when the browser or the Playwright MCP stops responding.', {},
69
+ async (c) => text(device.restartService(c, 'chromium')));
70
+ }
71
+
72
+ if (has(base, 'display')) {
73
+ tool('screenshot', 'PNG screenshot of the display the user watches (Linux: the virtual display in noVNC; macOS: the screen).', {},
74
+ async (c) => ({ content: [{ type: 'image', data: device.screenshot(c), mimeType: 'image/png' }] }));
75
+ }
76
+
77
+ if (has(base, 'playwright')) {
78
+ tool('run_tests_live', 'Run Playwright tests headed on the virtual display so the user can watch, streaming to logs/tests.log. Returns the exit code and the last part of the output.',
79
+ {
80
+ dir: z.string().describe('absolute path of the project (folder with playwright.config)'),
81
+ args: z.array(z.string()).optional().describe('extra playwright test args, e.g. ["tests/login.spec.ts", "--project=chromium"]'),
82
+ timeoutMinutes: z.number().int().min(1).max(120).optional(),
83
+ },
84
+ async (c, a) => {
85
+ if (!path.isAbsolute(a.dir) || !fs.existsSync(a.dir)) throw new Error(`Not an existing absolute path: ${a.dir}`);
86
+ return text(await device.runTestsLive(c, a.dir, a.args || [], (a.timeoutMinutes || 15) * 60000));
87
+ });
88
+ tool('playwright_ui', 'Open (or stop) Playwright UI mode for a project, for the user to watch and re-run tests interactively.',
89
+ { dir: z.string().optional(), stop: z.boolean().optional() },
90
+ async (c, a) => {
91
+ if (!a.stop && (!a.dir || !path.isAbsolute(a.dir) || !fs.existsSync(a.dir))) throw new Error('dir (an existing absolute path) is required unless stop is true');
92
+ return text(device.pwUi(c, a.dir, !!a.stop) + `\nURL: ${device.viewers(c.cfg, c.platform).playwrightUi}`);
93
+ });
94
+ }
95
+
96
+ if (has(base, 'docker')) {
97
+ tool('docker_summary', 'Containers (all) and Docker disk usage on this device.', {},
98
+ async (c) => text(device.dockerSummary(c)));
99
+ }
100
+
101
+ if (has(base, 'ngrok')) {
102
+ tool('ngrok_status', 'Public ngrok URLs currently open on this device (tunnels are opened by the user only).', {},
103
+ async () => text(await device.ngrokStatus()));
104
+ }
105
+
106
+ return server;
107
+ }
108
+
109
+ export async function serve(env = process.env) {
110
+ // stdout carries JSON-RPC only: anything else printed would corrupt it.
111
+ sendChildOutputToStderr();
112
+ console.log = console.info = (...a) => console.error(...a);
113
+ const server = buildServer(env);
114
+ await server.connect(new StdioServerTransport());
115
+ }
package/src/ngrok.js ADDED
@@ -0,0 +1,62 @@
1
+ // ngrok: every tunnel is defined, none runs until `harness-device ngrok up`.
2
+ // Viewers (noVNC, tmux web view, Playwright UI) always sit behind basic auth;
3
+ // app ports too, unless NGROK_APPS_PUBLIC=1.
4
+
5
+ export const GROUPS = ['viewers', 'apps'];
6
+
7
+ function appPorts(cfg) {
8
+ return String(cfg.NGROK_APP_PORTS || '').split(',').map((s) => s.trim()).filter(Boolean);
9
+ }
10
+
11
+ /** name → tunnel definition, grouped. */
12
+ export function tunnels(cfg, platformId = 'linux') {
13
+ const auth = [`${cfg.NGROK_VIEWER_USER}:${cfg.NGROK_VIEWER_PASS}`];
14
+ const t = {
15
+ viewers: {
16
+ // macOS has no noVNC (its screen is shared with Screen Sharing over SSH, which ngrok's HTTP tunnels can't carry).
17
+ ...(platformId === 'darwin' ? {} : { novnc: { addr: cfg.NOVNC_PORT, basic_auth: auth } }),
18
+ ttyd: { addr: cfg.TTYD_PORT, basic_auth: auth },
19
+ pwui: { addr: cfg.PW_UI_PORT, basic_auth: auth },
20
+ },
21
+ apps: {},
22
+ };
23
+ for (const p of appPorts(cfg)) {
24
+ t.apps[`app${p}`] = { addr: p, ...(String(cfg.NGROK_APPS_PUBLIC) === '1' ? {} : { basic_auth: auth }) };
25
+ }
26
+ // NGROK_DOMAIN (a reserved domain) goes on the first app port, else on the display viewer.
27
+ if (cfg.NGROK_DOMAIN) {
28
+ const first = Object.values(t.apps)[0] || t.viewers.novnc || t.viewers.ttyd;
29
+ first.domain = cfg.NGROK_DOMAIN;
30
+ }
31
+ return t;
32
+ }
33
+
34
+ export function selectTunnels(cfg, groups, platformId = 'linux') {
35
+ const all = tunnels(cfg, platformId);
36
+ const list = groups.includes('all') ? GROUPS : groups;
37
+ const bad = list.filter((g) => !GROUPS.includes(g));
38
+ if (bad.length) throw new Error(`Unknown ngrok group: ${bad.join(', ')} (use ${GROUPS.join(', ')} or all)`);
39
+ const names = list.flatMap((g) => Object.keys(all[g]));
40
+ if (!names.length) throw new Error(list.includes('apps') ? 'No app ports: set NGROK_APP_PORTS=3000,5173 in config.env' : 'Nothing to expose');
41
+ return names;
42
+ }
43
+
44
+ const y = (v) => JSON.stringify(String(v)); // JSON strings are valid YAML scalars
45
+
46
+ /** ngrok agent config (format version 2, understood by agent v3). */
47
+ export function renderNgrokYml(cfg, authtoken, platformId = 'linux') {
48
+ const all = tunnels(cfg, platformId);
49
+ const lines = ['version: "2"', `authtoken: ${y(authtoken)}`, 'tunnels:'];
50
+ for (const group of GROUPS) {
51
+ for (const [name, t] of Object.entries(all[group])) {
52
+ lines.push(` ${name}:`, ' proto: http', ` addr: ${y(`127.0.0.1:${t.addr}`)}`);
53
+ if (t.domain) lines.push(` domain: ${y(t.domain)}`);
54
+ if (t.basic_auth) lines.push(' basic_auth:', ...t.basic_auth.map((a) => ` - ${y(a)}`));
55
+ }
56
+ }
57
+ return lines.join('\n') + '\n';
58
+ }
59
+
60
+ export function renderNgrokEnv(names) {
61
+ return `HD_NGROK_TUNNELS='${names.join(' ')}'\n`;
62
+ }