@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
package/src/state.js ADDED
@@ -0,0 +1,197 @@
1
+ // Restart-safe state: which conversation each project slot is pinned to, and
2
+ // which long-running processes must come back. hd-tmux-layout rebuilds the
3
+ // whole tmux session from these files after any reboot.
4
+ //
5
+ // state/sessions/<project>/<slot> conversation id (uuid)
6
+ // state/sessions/<project>/<slot>.history ids this slot used before
7
+ // state/sessions/<project>/<slot>.failing present while the slot keeps failing
8
+ // state/procs/<name>.cmd / <name>.dir a registered process
9
+ // state/events.log restores, resets, failures
10
+
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import crypto from 'node:crypto';
15
+ import { NAME_RE } from './config.js';
16
+ import { capture, ok, run } from './util.js';
17
+
18
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
19
+
20
+ export function event(ctx, msg) {
21
+ fs.mkdirSync(ctx.paths.state, { recursive: true });
22
+ fs.appendFileSync(path.join(ctx.paths.state, 'events.log'), `${new Date().toISOString()}\t${msg}\n`);
23
+ }
24
+
25
+ function slotDir(ctx, project) {
26
+ return path.join(ctx.paths.state, 'sessions', project);
27
+ }
28
+
29
+ export function windowName(project, slot) {
30
+ return slot === 1 || slot === '1' ? `rc-${project}` : `rc-${project}-${slot}`;
31
+ }
32
+
33
+ /** The Claude transcript for a conversation id, if it exists. */
34
+ export function transcriptOf(id, env = process.env) {
35
+ const root = path.join(env.CLAUDE_CONFIG_DIR || path.join(env.HOME || os.homedir(), '.claude'), 'projects');
36
+ let dirs = [];
37
+ try { dirs = fs.readdirSync(root); } catch { return null; }
38
+ for (const d of dirs) {
39
+ const f = path.join(root, d, `${id}.jsonl`);
40
+ if (fs.existsSync(f)) return f;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ export function listSessions(ctx) {
46
+ const wins = capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}']).split('\n');
47
+ const out = [];
48
+ for (const p of ctx.projects) {
49
+ if (ctx.cfg.SERVE_MODE === 'server') {
50
+ out.push({ project: p.name, slot: '-', id: null, name: `${ctx.cfg.DEVICE}-${p.name}`, window: `rc-${p.name}`, running: wins.includes(`rc-${p.name}`) });
51
+ continue;
52
+ }
53
+ const dir = slotDir(ctx, p.name);
54
+ const slots = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d+$/.test(f)).map(Number).sort((a, b) => a - b) : [];
55
+ for (const slot of slots) {
56
+ const id = fs.readFileSync(path.join(dir, String(slot)), 'utf8').trim();
57
+ const t = transcriptOf(id, ctx.env);
58
+ const failing = fs.existsSync(path.join(dir, `${slot}.failing`));
59
+ const win = windowName(p.name, slot);
60
+ out.push({
61
+ project: p.name,
62
+ slot,
63
+ id,
64
+ name: `${ctx.cfg.DEVICE}-${p.name}${slot === 1 ? '' : `-${slot}`}`,
65
+ window: win,
66
+ running: wins.includes(win),
67
+ transcript: t,
68
+ lastActivity: t ? fs.statSync(t).mtime.toISOString() : null,
69
+ failing,
70
+ });
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function needSlot(slot) {
77
+ if (!/^[1-9]\d{0,3}$/.test(String(slot))) throw new Error(`Not a slot number: ${slot}`);
78
+ }
79
+
80
+ /** Write via a temp file and rename, so a crash never leaves a half-written conversation id. */
81
+ function writeAtomic(file, content) {
82
+ const tmp = `${file}.tmp-${process.pid}`;
83
+ fs.writeFileSync(tmp, content);
84
+ fs.renameSync(tmp, file);
85
+ }
86
+
87
+ function needProject(ctx, project) {
88
+ if (!ctx.projects.some((p) => p.name === project)) throw new Error(`No project "${project}" (projects: ${ctx.projects.map((p) => p.name).join(', ') || 'none'})`);
89
+ if (ctx.cfg.SERVE_MODE === 'server') throw new Error('Session slots are for SERVE_MODE=conversation; in server mode open new sessions from the Claude app.');
90
+ }
91
+
92
+ /** Add a slot: a second (third, ...) persistent conversation for a project. */
93
+ export function newSlot(ctx, project, id = crypto.randomUUID()) {
94
+ needProject(ctx, project);
95
+ if (!UUID_RE.test(id)) throw new Error(`Not a conversation id (uuid): ${id}`);
96
+ const dir = slotDir(ctx, project);
97
+ fs.mkdirSync(dir, { recursive: true });
98
+ // Exclusive create: two `session new` at once get different slots, never one shared.
99
+ const used = fs.readdirSync(dir).filter((f) => /^\d+$/.test(f)).map(Number);
100
+ let slot = used.length ? Math.max(...used) + 1 : 1;
101
+ for (;; slot++) {
102
+ try { fs.writeFileSync(path.join(dir, String(slot)), id + '\n', { flag: 'wx' }); break; } catch (e) { if (e.code !== 'EEXIST') throw e; }
103
+ }
104
+ event(ctx, `${project}/${slot} new conversation ${id}`);
105
+ return { slot, id };
106
+ }
107
+
108
+ /** Pin a slot to another conversation (a fresh one, or an existing id to adopt). */
109
+ export function setSlot(ctx, project, slot, id = crypto.randomUUID(), why = 'reset') {
110
+ needProject(ctx, project);
111
+ needSlot(slot);
112
+ if (!UUID_RE.test(id)) throw new Error(`Not a conversation id (uuid): ${id}`);
113
+ const f = path.join(slotDir(ctx, project), String(slot));
114
+ if (!fs.existsSync(f)) throw new Error(`No slot ${project}/${slot}`);
115
+ const old = fs.readFileSync(f, 'utf8').trim();
116
+ fs.appendFileSync(`${f}.history`, old + '\n');
117
+ writeAtomic(f, id + '\n');
118
+ fs.rmSync(`${f}.failing`, { force: true });
119
+ event(ctx, `${project}/${slot} ${why}: ${old} → ${id}`);
120
+ restartWindow(ctx, windowName(project, slot));
121
+ return { slot: Number(slot), old, id };
122
+ }
123
+
124
+ export function removeSlot(ctx, project, slot) {
125
+ needProject(ctx, project);
126
+ needSlot(slot);
127
+ const f = path.join(slotDir(ctx, project), String(slot));
128
+ if (!fs.existsSync(f)) throw new Error(`No slot ${project}/${slot}`);
129
+ const id = fs.readFileSync(f, 'utf8').trim();
130
+ fs.appendFileSync(`${f}.history`, id + '\n');
131
+ fs.rmSync(f);
132
+ fs.rmSync(`${f}.failing`, { force: true });
133
+ event(ctx, `${project}/${slot} removed (conversation ${id} kept on disk)`);
134
+ ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:${windowName(project, slot)}`]);
135
+ return { id };
136
+ }
137
+
138
+ /** Register a process that must survive reboots (dev server, watcher, worker). */
139
+ export function addProc(ctx, name, dir, command) {
140
+ if (!NAME_RE.test(name)) throw new Error('Process name must be letters, digits, _ or -.');
141
+ if (!path.isAbsolute(dir) || !fs.existsSync(dir)) throw new Error(`Not an existing absolute directory: ${dir}`);
142
+ if (!command || /\n/.test(command)) throw new Error('Give the command as one line.');
143
+ const d = path.join(ctx.paths.state, 'procs');
144
+ fs.mkdirSync(d, { recursive: true });
145
+ fs.writeFileSync(path.join(d, `${name}.cmd`), command + '\n');
146
+ fs.writeFileSync(path.join(d, `${name}.dir`), dir + '\n');
147
+ event(ctx, `proc ${name} registered: ${command} (in ${dir})`);
148
+ restartWindow(ctx, `proc-${name}`);
149
+ }
150
+
151
+ export function removeProc(ctx, name) {
152
+ if (!NAME_RE.test(name || '')) throw new Error('Process name must be letters, digits, _ or -.');
153
+ const d = path.join(ctx.paths.state, 'procs');
154
+ if (!fs.existsSync(path.join(d, `${name}.cmd`))) throw new Error(`No registered process "${name}"`);
155
+ fs.rmSync(path.join(d, `${name}.cmd`));
156
+ fs.rmSync(path.join(d, `${name}.dir`), { force: true });
157
+ event(ctx, `proc ${name} removed`);
158
+ ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:proc-${name}`]);
159
+ }
160
+
161
+ export function listProcs(ctx) {
162
+ const d = path.join(ctx.paths.state, 'procs');
163
+ if (!fs.existsSync(d)) return [];
164
+ const wins = capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}']).split('\n');
165
+ return fs.readdirSync(d).filter((f) => f.endsWith('.cmd')).map((f) => {
166
+ const name = f.slice(0, -4);
167
+ return {
168
+ name,
169
+ command: fs.readFileSync(path.join(d, f), 'utf8').trim(),
170
+ dir: fs.existsSync(path.join(d, `${name}.dir`)) ? fs.readFileSync(path.join(d, `${name}.dir`), 'utf8').trim() : (ctx.env.HOME || os.homedir()),
171
+ running: wins.includes(`proc-${name}`),
172
+ };
173
+ });
174
+ }
175
+
176
+ export function recentEvents(ctx, n = 30) {
177
+ const f = path.join(ctx.paths.state, 'events.log');
178
+ return fs.existsSync(f) ? fs.readFileSync(f, 'utf8').trim().split('\n').slice(-n) : [];
179
+ }
180
+
181
+ /**
182
+ * Bring tmux in line with the state files. With a live session, the layout
183
+ * script tops windows up (the tmux server spawns them, in its own cgroup);
184
+ * with none, the unit is restarted so the server is owned by systemd.
185
+ */
186
+ export function applyLayout(ctx) {
187
+ if (ok('tmux', ['has-session', '-t', `=${ctx.cfg.SESSION}`])) {
188
+ run(path.join(ctx.paths.bin, 'hd-tmux-layout'), [], { env: ctx.env, allowFail: true });
189
+ } else {
190
+ ctx.platform.restart(ctx, 'harness-tmux');
191
+ }
192
+ }
193
+
194
+ function restartWindow(ctx, win) {
195
+ ok('tmux', ['kill-window', '-t', `=${ctx.cfg.SESSION}:${win}`]);
196
+ if (fs.existsSync(path.join(ctx.paths.bin, 'hd-tmux-layout'))) applyLayout(ctx);
197
+ }
package/src/util.js ADDED
@@ -0,0 +1,103 @@
1
+ import { spawnSync, execFileSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ export const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
7
+ export const PKG = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8'));
8
+
9
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
10
+ const c = (code) => (s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
11
+ export const color = { dim: c(2), bold: c(1), red: c(31), green: c(32), yellow: c(33), cyan: c(36) };
12
+
13
+ export const log = {
14
+ step: (m) => console.log(`${color.cyan('›')} ${m}`),
15
+ ok: (m) => console.log(`${color.green('✓')} ${m}`),
16
+ warn: (m) => console.log(`${color.yellow('!')} ${m}`),
17
+ err: (m) => console.error(`${color.red('✗')} ${m}`),
18
+ info: (m) => console.log(m),
19
+ };
20
+
21
+ export function which(cmd, env = process.env) {
22
+ for (const dir of String(env.PATH || '').split(':')) {
23
+ if (!dir) continue;
24
+ const p = path.join(dir, cmd);
25
+ try {
26
+ fs.accessSync(p, fs.constants.X_OK);
27
+ if (fs.statSync(p).isFile()) return p;
28
+ } catch {}
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /** Run a command, inheriting stdio. In dry-run mode only print it. Throws on failure unless allowFail. */
34
+ // The MCP server speaks JSON-RPC on stdout: it sends child output to stderr.
35
+ let childOut = 'inherit';
36
+ export function sendChildOutputToStderr() { childOut = process.stderr; }
37
+
38
+ export function run(cmd, args = [], { dryRun = false, allowFail = false, env, cwd, input } = {}) {
39
+ const shown = [cmd, ...args].map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : JSON.stringify(a))).join(' ');
40
+ if (dryRun) {
41
+ console.log(color.dim(` $ ${shown}`));
42
+ return { status: 0, dry: true };
43
+ }
44
+ const r = spawnSync(cmd, args, { stdio: [input != null ? 'pipe' : 'inherit', childOut, 'inherit'], env, cwd, input });
45
+ if ((r.status !== 0 || r.error) && !allowFail) {
46
+ throw new Error(`Command failed (${r.error ? r.error.code : `exit ${r.status}`}): ${shown}`);
47
+ }
48
+ return r;
49
+ }
50
+
51
+ /** Capture stdout; returns '' on failure. */
52
+ export function capture(cmd, args = [], { timeout = 15000, env, cwd } = {}) {
53
+ try {
54
+ return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout, env, cwd }).trim();
55
+ } catch {
56
+ return '';
57
+ }
58
+ }
59
+
60
+ export function ok(cmd, args = [], opts = {}) {
61
+ try {
62
+ execFileSync(cmd, args, { stdio: 'ignore', timeout: opts.timeout || 15000, env: opts.env });
63
+ return true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ export function writeFile(file, content, { mode, dryRun } = {}) {
70
+ if (dryRun) {
71
+ console.log(color.dim(` write ${file}`));
72
+ return;
73
+ }
74
+ fs.mkdirSync(path.dirname(file), { recursive: true });
75
+ fs.writeFileSync(file, content, mode ? { mode } : undefined);
76
+ if (mode) fs.chmodSync(file, mode);
77
+ }
78
+
79
+ /** Replace {{KEY}} placeholders; throws if any remain unfilled. */
80
+ export function render(template, vars, name = 'template') {
81
+ const out = template.replace(/\{\{([A-Z0-9_]+)\}\}/g, (m, k) => (k in vars ? String(vars[k]) : m));
82
+ const left = out.match(/\{\{[A-Z0-9_]+\}\}/g);
83
+ if (left) throw new Error(`${name}: unfilled ${[...new Set(left)].join(', ')}`);
84
+ return out;
85
+ }
86
+
87
+ export async function httpOk(url, timeoutMs = 3000) {
88
+ try {
89
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
90
+ return res.ok;
91
+ } catch {
92
+ return false;
93
+ }
94
+ }
95
+
96
+ export async function httpJson(url, timeoutMs = 3000) {
97
+ try {
98
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
99
+ return res.ok ? await res.json() : null;
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
@@ -0,0 +1,17 @@
1
+ [Unit]
2
+ Description=harness-device: Chromium (persistent profile, CDP 127.0.0.1:{{CDP_PORT}})
3
+ BindsTo=harness-xvfb.service
4
+ After=harness-xvfb.service
5
+ PartOf=harness.target
6
+
7
+ [Service]
8
+ EnvironmentFile={{HD_HOME}}/runtime.env
9
+ ExecStart={{HD_HOME}}/bin/hd-chromium
10
+ Restart=always
11
+ RestartSec=3
12
+ # Let Chromium flush cookies and the profile on stop.
13
+ KillSignal=SIGTERM
14
+ TimeoutStopSec=20
15
+
16
+ [Install]
17
+ WantedBy=harness.target
@@ -0,0 +1,7 @@
1
+ [Unit]
2
+ Description=harness-device: restart dead services, rebuild tmux windows
3
+
4
+ [Service]
5
+ Type=oneshot
6
+ EnvironmentFile={{HD_HOME}}/runtime.env
7
+ ExecStart={{HD_HOME}}/bin/hd-heal
@@ -0,0 +1,10 @@
1
+ [Unit]
2
+ Description=harness-device: self-heal every {{HEAL_INTERVAL}}
3
+ PartOf=harness.target
4
+
5
+ [Timer]
6
+ OnBootSec=1min
7
+ OnUnitActiveSec={{HEAL_INTERVAL}}
8
+
9
+ [Install]
10
+ WantedBy=harness.target
@@ -0,0 +1,13 @@
1
+ [Unit]
2
+ Description=harness-device: ngrok tunnels (enabled only by `harness-device ngrok up`)
3
+ After=network-online.target
4
+
5
+ [Service]
6
+ EnvironmentFile={{HD_HOME}}/runtime.env
7
+ EnvironmentFile={{HD_HOME}}/ngrok.env
8
+ ExecStart=/usr/bin/env ngrok start --config {{HD_HOME}}/ngrok.yml --log stdout --log-format logfmt $HD_NGROK_TUNNELS
9
+ Restart=always
10
+ RestartSec=10
11
+
12
+ [Install]
13
+ WantedBy=default.target
@@ -0,0 +1,14 @@
1
+ [Unit]
2
+ Description=harness-device: noVNC browser viewer on 127.0.0.1:{{NOVNC_PORT}}
3
+ After=harness-vnc.service
4
+ Wants=harness-vnc.service
5
+ PartOf=harness.target
6
+
7
+ [Service]
8
+ EnvironmentFile={{HD_HOME}}/runtime.env
9
+ ExecStart=/usr/bin/websockify --web {{NOVNC_WEB}} 127.0.0.1:{{NOVNC_PORT}} 127.0.0.1:{{VNC_PORT}}
10
+ Restart=always
11
+ RestartSec=3
12
+
13
+ [Install]
14
+ WantedBy=harness.target
@@ -0,0 +1,15 @@
1
+ [Unit]
2
+ Description=harness-device: tmux session {{SESSION}} with Claude Remote Control per project
3
+ After=harness-chromium.service network-online.target
4
+ Wants=harness-chromium.service
5
+ PartOf=harness.target
6
+
7
+ [Service]
8
+ Type=oneshot
9
+ RemainAfterExit=yes
10
+ EnvironmentFile={{HD_HOME}}/runtime.env
11
+ ExecStart={{HD_HOME}}/bin/hd-tmux-layout
12
+ ExecStop=-/usr/bin/env tmux kill-session -t ={{SESSION}}
13
+
14
+ [Install]
15
+ WantedBy=harness.target
@@ -0,0 +1,14 @@
1
+ [Unit]
2
+ Description=harness-device: read-only web view of tmux on 127.0.0.1:{{TTYD_PORT}}
3
+ After=harness-tmux.service
4
+ Wants=harness-tmux.service
5
+ PartOf=harness.target
6
+
7
+ [Service]
8
+ EnvironmentFile={{HD_HOME}}/runtime.env
9
+ ExecStart={{TTYD_BIN}} -i lo -p {{TTYD_PORT}} -t titleFixed=harness-device /usr/bin/env tmux attach -r -f ignore-size -t ={{SESSION}}
10
+ Restart=always
11
+ RestartSec=5
12
+
13
+ [Install]
14
+ WantedBy=harness.target
@@ -0,0 +1,14 @@
1
+ [Unit]
2
+ Description=harness-device: VNC of display :{{DISPLAY_NUM}} (localhost only)
3
+ BindsTo=harness-xvfb.service
4
+ After=harness-xvfb.service
5
+ PartOf=harness.target
6
+
7
+ [Service]
8
+ EnvironmentFile={{HD_HOME}}/runtime.env
9
+ ExecStart=/usr/bin/x11vnc -display :{{DISPLAY_NUM}} -localhost -rfbport {{VNC_PORT}} -forever -shared -nopw -quiet -noxdamage
10
+ Restart=always
11
+ RestartSec=3
12
+
13
+ [Install]
14
+ WantedBy=harness.target
@@ -0,0 +1,13 @@
1
+ [Unit]
2
+ Description=harness-device: virtual display :{{DISPLAY_NUM}}
3
+ PartOf=harness.target
4
+
5
+ [Service]
6
+ EnvironmentFile={{HD_HOME}}/runtime.env
7
+ ExecStartPre=-/bin/rm -f /tmp/.X{{DISPLAY_NUM}}-lock /tmp/.X11-unix/X{{DISPLAY_NUM}}
8
+ ExecStart=/usr/bin/Xvfb :{{DISPLAY_NUM}} -screen 0 {{SCREEN}} -nolisten tcp -ac
9
+ Restart=always
10
+ RestartSec=2
11
+
12
+ [Install]
13
+ WantedBy=harness.target
@@ -0,0 +1,6 @@
1
+ [Unit]
2
+ Description=harness-device: {{DEVICE}} (capabilities: {{CAPABILITIES}})
3
+ Wants={{WANTS}}
4
+
5
+ [Install]
6
+ WantedBy=default.target