@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.
- package/CHANGELOG.md +13 -0
- package/LICENSE +21 -0
- package/README.md +255 -2
- package/bin/harness-device.js +8 -0
- package/package.json +62 -4
- package/sh/bin/hd-chromium +51 -0
- package/sh/bin/hd-heal +31 -0
- package/sh/bin/hd-lib.sh +74 -0
- package/sh/bin/hd-ngrok +7 -0
- package/sh/bin/hd-proc-loop +23 -0
- package/sh/bin/hd-pw-live +33 -0
- package/sh/bin/hd-rc-loop +42 -0
- package/sh/bin/hd-run +6 -0
- package/sh/bin/hd-serve-claude +23 -0
- package/sh/bin/hd-tmux-layout +69 -0
- package/sh/bin/hd-tmux-supervise +11 -0
- package/sh/bin/hd-with-secrets +8 -0
- package/sh/setup/darwin.sh +75 -0
- package/sh/setup/linux.sh +118 -0
- package/src/capabilities.js +237 -0
- package/src/cli.js +382 -0
- package/src/config.js +239 -0
- package/src/context.js +54 -0
- package/src/device.js +127 -0
- package/src/doctor.js +40 -0
- package/src/fleet.js +94 -0
- package/src/install.js +91 -0
- package/src/mcp/server.js +115 -0
- package/src/ngrok.js +62 -0
- package/src/platform/darwin.js +190 -0
- package/src/platform/index.js +12 -0
- package/src/platform/linux.js +142 -0
- package/src/providers/claude.js +212 -0
- package/src/state.js +197 -0
- package/src/util.js +103 -0
- package/templates/systemd/harness-chromium.service +17 -0
- package/templates/systemd/harness-heal.service +7 -0
- package/templates/systemd/harness-heal.timer +10 -0
- package/templates/systemd/harness-ngrok.service +13 -0
- package/templates/systemd/harness-novnc.service +14 -0
- package/templates/systemd/harness-tmux.service +15 -0
- package/templates/systemd/harness-ttyd.service +14 -0
- package/templates/systemd/harness-vnc.service +14 -0
- package/templates/systemd/harness-xvfb.service +13 -0
- package/templates/systemd/harness.target +6 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import readline from 'node:readline';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths } from './config.js';
|
|
7
|
+
import { ORDER, CAPABILITIES } from './capabilities.js';
|
|
8
|
+
import { loadContext } from './context.js';
|
|
9
|
+
import { install, uninstall } from './install.js';
|
|
10
|
+
import * as doctor from './doctor.js';
|
|
11
|
+
import * as device from './device.js';
|
|
12
|
+
import * as state from './state.js';
|
|
13
|
+
import * as ngrok from './ngrok.js';
|
|
14
|
+
import * as fleet from './fleet.js';
|
|
15
|
+
import { PKG, log, color, run, writeFile, capture } from './util.js';
|
|
16
|
+
|
|
17
|
+
const HELP = `${color.bold('harness-device')} ${PKG.version}: a reboot-proof dev device for remote AI agents (Claude Remote Control first)
|
|
18
|
+
|
|
19
|
+
${color.bold('Set up')}
|
|
20
|
+
init [--device <name>] [--project name:/dir ...] [--with cap,...] [--without cap,...] [--serve-mode conversation|server]
|
|
21
|
+
[--dokploy-url https://your-dokploy]
|
|
22
|
+
install [--dry-run] [--skip-system] install or update everything (idempotent; never drops live sessions)
|
|
23
|
+
doctor check everything, with fixes
|
|
24
|
+
uninstall [--purge]
|
|
25
|
+
|
|
26
|
+
${color.bold('Projects and sessions')} (survive reboots: each slot resumes its own conversation)
|
|
27
|
+
project add name:/dir | rm <name> | list
|
|
28
|
+
session list slots, conversation ids, last activity
|
|
29
|
+
session new <project> another persistent conversation for a project
|
|
30
|
+
session reset <project> [slot] start a fresh conversation in a slot (old id kept in history)
|
|
31
|
+
session adopt <project> <slot> <id> pin a slot to an existing conversation id
|
|
32
|
+
session rm <project> <slot>
|
|
33
|
+
proc add <name> <dir> '<command>' keep a process running across crashes and reboots
|
|
34
|
+
proc rm <name> | list
|
|
35
|
+
attach [project|window] open the tmux session (Ctrl-b d to detach)
|
|
36
|
+
logs <project|rc-…|proc-…|tests|service> [-n 100] [-f]
|
|
37
|
+
events restores, resets and failures, newest last
|
|
38
|
+
|
|
39
|
+
${color.bold('Device')}
|
|
40
|
+
status [--json] sessions, processes, services, viewers
|
|
41
|
+
tunnel ssh command to watch the display, tmux and Playwright UI
|
|
42
|
+
secrets set <KEY> | list | rm <KEY> API keys for MCP servers (kept out of agent sessions)
|
|
43
|
+
ngrok token | up <viewers|apps|all>... | down | status
|
|
44
|
+
restart <service> restart one harness service (chromium, ttyd, ...)
|
|
45
|
+
mcp run the harness-device MCP server (stdio)
|
|
46
|
+
|
|
47
|
+
${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
48
|
+
fleet add <name> <user@host> | rm <name> | list
|
|
49
|
+
fleet status every device's sessions and services
|
|
50
|
+
fleet run <name> <harness-device args> e.g. fleet run box1 install
|
|
51
|
+
|
|
52
|
+
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
53
|
+
`;
|
|
54
|
+
|
|
55
|
+
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'json', 'purge', 'force', 'follow', 'help', 'version'];
|
|
56
|
+
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl'];
|
|
57
|
+
|
|
58
|
+
// Commands whose tail is someone else's command line, kept verbatim:
|
|
59
|
+
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
60
|
+
const rawTail = (pos) => (pos[0] === 'proc' && pos[1] === 'add' && pos.length === 4) || (pos[0] === 'fleet' && pos[1] === 'run' && pos.length === 3);
|
|
61
|
+
|
|
62
|
+
export function flags(argv) {
|
|
63
|
+
const out = { _: [] };
|
|
64
|
+
for (let i = 0; i < argv.length; i++) {
|
|
65
|
+
if (rawTail(out._)) {
|
|
66
|
+
const tail = argv.slice(i);
|
|
67
|
+
out._.push(...(tail[0] === '--' ? tail.slice(1) : tail));
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
const a = argv[i];
|
|
71
|
+
if (a === '--') { out._.push(...argv.slice(i + 1)); break; }
|
|
72
|
+
if (a.startsWith('--')) {
|
|
73
|
+
const eq = a.indexOf('=');
|
|
74
|
+
const k = eq < 0 ? a.slice(2) : a.slice(2, eq);
|
|
75
|
+
const key = k.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
76
|
+
let val;
|
|
77
|
+
if (eq >= 0) val = a.slice(eq + 1);
|
|
78
|
+
else if (BOOL_FLAGS.includes(key)) val = true;
|
|
79
|
+
else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) val = argv[++i];
|
|
80
|
+
else if (VALUE_FLAGS.includes(key)) throw new Error(`--${k} needs a value`);
|
|
81
|
+
else val = true;
|
|
82
|
+
if (key === 'project') (out.project = out.project || []).push(val);
|
|
83
|
+
else out[key] = val;
|
|
84
|
+
} else if (a === '-n') out.n = argv[++i];
|
|
85
|
+
else if (a === '-f') out.follow = true;
|
|
86
|
+
else if (a === '-h') out.help = true;
|
|
87
|
+
else out._.push(a);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function readSecret(prompt) {
|
|
93
|
+
if (!process.stdin.isTTY) return fs.readFileSync(0, 'utf8').trim();
|
|
94
|
+
return new Promise((resolve) => {
|
|
95
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
96
|
+
rl._writeToOutput = (s) => { if (s.includes(prompt)) process.stdout.write(s); };
|
|
97
|
+
rl.question(prompt, (v) => { rl.close(); process.stdout.write('\n'); resolve(v.trim()); });
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The tmux window this command runs in, if any (to stop an agent killing its own session). */
|
|
102
|
+
function ownWindow() {
|
|
103
|
+
if (!process.env.TMUX_PANE) return null;
|
|
104
|
+
return capture('tmux', ['display-message', '-p', '-t', process.env.TMUX_PANE, '#{window_name}']) || null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function guardOwn(ctx, win, f) {
|
|
108
|
+
if (win && win === ownWindow() && !f.force) throw new Error(`That would restart the window this command runs in (${win}), ending this session. Run it from another window, or add --force.`);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function refreshProjects(ctx) {
|
|
112
|
+
if (!fs.existsSync(ctx.paths.runtimeEnv)) return log.info(color.dim('Not installed yet: run harness-device install.'));
|
|
113
|
+
writeFile(ctx.paths.projects, renderProjectsTsv(ctx.cfg), { mode: 0o600 });
|
|
114
|
+
state.applyLayout(ctx);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function setSecret(file, key, value) {
|
|
118
|
+
const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter((l) => !l.startsWith(`${key}=`)) : [];
|
|
119
|
+
while (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
120
|
+
if (value != null) lines.push(`${key}='${value}'`);
|
|
121
|
+
writeFile(file, lines.join('\n') + '\n', { mode: 0o600 });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function printStatus(s) {
|
|
125
|
+
console.log(`${color.bold(s.device)} ${color.dim(`· ${s.provider} · ${s.serveMode} mode · ${s.capabilities.join(', ')}`)}`);
|
|
126
|
+
console.log(color.bold('\nsessions'));
|
|
127
|
+
if (!s.sessions.length) console.log(color.dim(' none (harness-device project add name:/dir)'));
|
|
128
|
+
for (const x of s.sessions) {
|
|
129
|
+
const mark = x.failing ? color.red('✗') : x.running ? color.green('●') : color.red('○');
|
|
130
|
+
const conv = x.id ? color.dim(`${x.id}${x.lastActivity ? ` last activity ${x.lastActivity.slice(0, 16).replace('T', ' ')}` : ' (new)'}`) : '';
|
|
131
|
+
console.log(` ${mark} ${x.name.padEnd(28)} ${conv}${x.failing ? color.red(' failing') : ''}`);
|
|
132
|
+
}
|
|
133
|
+
if (s.procs.length) {
|
|
134
|
+
console.log(color.bold('\nprocesses'));
|
|
135
|
+
for (const p of s.procs) console.log(` ${p.running ? color.green('●') : color.red('○')} ${p.name.padEnd(20)} ${color.dim(`${p.command} (${p.dir})`)}`);
|
|
136
|
+
}
|
|
137
|
+
console.log(color.bold('\nservices'));
|
|
138
|
+
console.log(' ' + s.services.map((x) => `${x.state === 'active' ? color.green('●') : color.red('○')} ${x.unit.replace(/^harness-/, '')}`).join(' '));
|
|
139
|
+
console.log(color.bold('\nviewers') + color.dim(' (127.0.0.1; harness-device tunnel)'));
|
|
140
|
+
console.log(` display ${s.viewers.novnc}\n tmux ${s.viewers.tmux}`);
|
|
141
|
+
console.log(`\n${color.dim(s.load)}`);
|
|
142
|
+
if (s.browser) console.log(color.dim(`browser: ${s.browser}`));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export async function main(argv) {
|
|
146
|
+
const f = flags(argv);
|
|
147
|
+
const [cmd, sub, ...rest] = f._;
|
|
148
|
+
const env = process.env;
|
|
149
|
+
// Never let --help or --version fall through into a command that changes things.
|
|
150
|
+
if (f.version) return console.log(PKG.version);
|
|
151
|
+
if (f.help) return console.log(HELP);
|
|
152
|
+
|
|
153
|
+
switch (cmd) {
|
|
154
|
+
case undefined:
|
|
155
|
+
case 'help':
|
|
156
|
+
case '--help':
|
|
157
|
+
return console.log(HELP);
|
|
158
|
+
case 'version':
|
|
159
|
+
case '--version':
|
|
160
|
+
return console.log(PKG.version);
|
|
161
|
+
|
|
162
|
+
case 'init': {
|
|
163
|
+
const { cfg, exists } = loadConfig(env);
|
|
164
|
+
if (f.device) cfg.DEVICE = String(f.device);
|
|
165
|
+
if (f.provider) cfg.PROVIDER = String(f.provider);
|
|
166
|
+
if (f.dokployUrl) cfg.DOKPLOY_URL = String(f.dokployUrl).replace(/\/+$/, '');
|
|
167
|
+
if (f.serveMode) cfg.SERVE_MODE = String(f.serveMode);
|
|
168
|
+
if (f.capabilities) cfg.CAPABILITIES = String(f.capabilities);
|
|
169
|
+
if (f.with) cfg.CAPABILITIES = [...new Set([...String(cfg.CAPABILITIES).split(','), ...String(f.with).split(',')].map((s) => s.trim()).filter(Boolean))].join(',');
|
|
170
|
+
if (f.without) { const drop = String(f.without).split(','); cfg.CAPABILITIES = String(cfg.CAPABILITIES).split(',').filter((c) => !drop.includes(c)).join(','); }
|
|
171
|
+
for (const spec of f.project || []) { const p = parseProjectSpec(spec, env); cfg[`PROJECT_${p.name}`] = p.dir; }
|
|
172
|
+
const errs = validateConfig(cfg, env);
|
|
173
|
+
if (errs.length) throw new Error(errs.join('\n'));
|
|
174
|
+
loadContext(env); // validates capability names
|
|
175
|
+
saveConfig(cfg, env);
|
|
176
|
+
log.ok(`${exists ? 'Updated' : 'Wrote'} ${getPaths(env).config}`);
|
|
177
|
+
log.info(color.dim(`device ${cfg.DEVICE} · capabilities ${cfg.CAPABILITIES} · ${cfg.SERVE_MODE} mode`));
|
|
178
|
+
return log.info(`Next: ${color.bold('harness-device install')}`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
case 'install': {
|
|
182
|
+
const ctx = loadContext(env, { dryRun: !!f.dryRun });
|
|
183
|
+
return install(ctx, { skipSystem: !!f.skipSystem });
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
case 'uninstall':
|
|
187
|
+
return uninstall(loadContext(env, { dryRun: !!f.dryRun }), { purge: !!f.purge });
|
|
188
|
+
|
|
189
|
+
case 'doctor': {
|
|
190
|
+
const bad = doctor.print(await doctor.collect(loadContext(env)));
|
|
191
|
+
process.exitCode = bad ? 1 : 0;
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
case 'status': {
|
|
196
|
+
const ctx = loadContext(env);
|
|
197
|
+
const s = await device.status(ctx);
|
|
198
|
+
return f.json ? console.log(JSON.stringify(s, null, 2)) : printStatus(s);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
case 'project': {
|
|
202
|
+
const { cfg } = loadConfig(env);
|
|
203
|
+
if (sub === 'add') {
|
|
204
|
+
const p = parseProjectSpec(rest[0] || '', env);
|
|
205
|
+
cfg[`PROJECT_${p.name}`] = p.dir;
|
|
206
|
+
saveConfig(cfg, env);
|
|
207
|
+
log.ok(`Project ${p.name} → ${p.dir}`);
|
|
208
|
+
} else if (sub === 'rm') {
|
|
209
|
+
if (!cfg[`PROJECT_${rest[0]}`]) throw new Error(`No project "${rest[0]}"`);
|
|
210
|
+
const own = ownWindow();
|
|
211
|
+
if (own && new RegExp(`^rc-${rest[0]}(-\\d+)?$`).test(own) && !f.force) throw new Error(`That would close the window this command runs in (${own}), ending this session. Run it from another window, or add --force.`);
|
|
212
|
+
delete cfg[`PROJECT_${rest[0]}`];
|
|
213
|
+
saveConfig(cfg, env);
|
|
214
|
+
log.ok(`Removed project ${rest[0]} (its conversation ids stay in ~/.harness-device/state/sessions/${rest[0]}; re-adding it resumes them)`);
|
|
215
|
+
} else {
|
|
216
|
+
const ctx = loadContext(env);
|
|
217
|
+
for (const p of ctx.projects) console.log(`${p.name}\t${p.dir}`);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
return refreshProjects(loadContext(env));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
case 'session':
|
|
224
|
+
case 'sessions': {
|
|
225
|
+
const ctx = loadContext(env);
|
|
226
|
+
if (!sub || sub === 'list') {
|
|
227
|
+
const list = state.listSessions(ctx);
|
|
228
|
+
if (f.json) return console.log(JSON.stringify(list, null, 2));
|
|
229
|
+
for (const x of list) console.log(`${x.name}\t${x.window}\t${x.id || '(server mode)'}\t${x.lastActivity || '-'}${x.failing ? '\tFAILING' : ''}`);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (sub === 'new') {
|
|
233
|
+
const r = state.newSlot(ctx, rest[0]);
|
|
234
|
+
log.ok(`${rest[0]} slot ${r.slot}: conversation ${r.id} (window ${state.windowName(rest[0], r.slot)})`);
|
|
235
|
+
return state.applyLayout(ctx);
|
|
236
|
+
}
|
|
237
|
+
if (sub === 'reset' || sub === 'adopt') {
|
|
238
|
+
const [project, slot = '1', id] = rest;
|
|
239
|
+
if (sub === 'adopt' && !id) throw new Error('usage: session adopt <project> <slot> <conversation-id>');
|
|
240
|
+
guardOwn(ctx, state.windowName(project, slot), f);
|
|
241
|
+
const r = state.setSlot(ctx, project, slot, id, sub);
|
|
242
|
+
return log.ok(`${project}/${r.slot}: ${r.old} → ${r.id}`);
|
|
243
|
+
}
|
|
244
|
+
if (sub === 'rm') {
|
|
245
|
+
guardOwn(ctx, state.windowName(rest[0], rest[1]), f);
|
|
246
|
+
const r = state.removeSlot(ctx, rest[0], rest[1]);
|
|
247
|
+
return log.ok(`Removed slot ${rest[0]}/${rest[1]} (conversation ${r.id} stays on disk)`);
|
|
248
|
+
}
|
|
249
|
+
throw new Error(`Unknown: session ${sub}`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
case 'proc': {
|
|
253
|
+
const ctx = loadContext(env);
|
|
254
|
+
if (sub === 'add') {
|
|
255
|
+
const [name, dir, ...cmdParts] = rest;
|
|
256
|
+
if (!cmdParts.length) throw new Error("usage: proc add <name> <dir> '<command>'");
|
|
257
|
+
guardOwn(ctx, `proc-${name}`, f);
|
|
258
|
+
state.addProc(ctx, name, path.resolve(dir), cmdParts.join(' '));
|
|
259
|
+
return log.ok(`proc ${name} registered; running in tmux window proc-${name}`);
|
|
260
|
+
}
|
|
261
|
+
if (sub === 'rm') { guardOwn(ctx, `proc-${rest[0]}`, f); state.removeProc(ctx, rest[0]); return log.ok(`proc ${rest[0]} removed`); }
|
|
262
|
+
for (const p of state.listProcs(ctx)) console.log(`${p.running ? '●' : '○'} ${p.name}\t${p.dir}\t${p.command}`);
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
case 'events': {
|
|
267
|
+
const ctx = loadContext(env);
|
|
268
|
+
return console.log(state.recentEvents(ctx, Number(f.n) || 50).join('\n') || '(no events yet)');
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
case 'attach': {
|
|
272
|
+
const ctx = loadContext(env);
|
|
273
|
+
const target = sub ? (sub.startsWith('rc-') || sub.startsWith('proc-') ? sub : `rc-${sub}`) : null;
|
|
274
|
+
const t = `=${ctx.cfg.SESSION}${target ? `:${target}` : ''}`;
|
|
275
|
+
const r = spawnSync('tmux', process.env.TMUX ? ['switch-client', '-t', t] : ['attach', '-t', t], { stdio: 'inherit' });
|
|
276
|
+
process.exitCode = r.status ?? 1;
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
case 'logs': {
|
|
281
|
+
const ctx = loadContext(env);
|
|
282
|
+
if (!sub) throw new Error('usage: logs <project|rc-…|proc-…|tests|service> [-n 100] [-f]');
|
|
283
|
+
if (f.follow) {
|
|
284
|
+
const proj = ctx.projects.find((p) => p.name === sub);
|
|
285
|
+
const file = path.join(ctx.paths.logs, proj ? `rc-${proj.name}.log` : `${sub}.log`);
|
|
286
|
+
if (fs.existsSync(file)) return void spawnSync('tail', ['-n', String(f.n || 100), '-F', file], { stdio: 'inherit' });
|
|
287
|
+
const [c, a] = ctx.platform.followLogsCmd(sub.startsWith('harness-') ? sub : `harness-${sub}`, ctx);
|
|
288
|
+
return void spawnSync(c, a, { stdio: 'inherit', env: ctx.env });
|
|
289
|
+
}
|
|
290
|
+
return console.log(device.logs(ctx, sub, f.n));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
case 'tunnel': {
|
|
294
|
+
const ctx = loadContext(env);
|
|
295
|
+
const host = `${env.USER || os.userInfo().username}@${os.hostname()}`;
|
|
296
|
+
log.info(`Run on your laptop:\n\n ${color.bold(device.tunnelCommand(ctx.cfg, ctx.platform, host))}\n`);
|
|
297
|
+
const v = device.viewers(ctx.cfg, ctx.platform);
|
|
298
|
+
return log.info(`Then open:\n display ${v.display}\n tmux (r/o) ${v.tmux}\n Playwright ${v.playwrightUi} (while hd-pw-live ui runs)`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
case 'secrets': {
|
|
302
|
+
const p = getPaths(env);
|
|
303
|
+
if (sub === 'set') {
|
|
304
|
+
const key = rest[0];
|
|
305
|
+
if (!/^[A-Z][A-Z0-9_]*$/.test(key || '')) throw new Error('usage: secrets set KEY (KEY in UPPER_SNAKE_CASE; value read hidden from the terminal or stdin)');
|
|
306
|
+
if (/^(ANTHROPIC_|CLAUDE_CODE_USE_)/.test(key)) throw new Error(`${key} would make Claude Code skip the claude.ai login that Remote Control needs; not stored.`);
|
|
307
|
+
const v = await readSecret(`${key}: `);
|
|
308
|
+
if (!v || /['\n]/.test(v)) throw new Error('Empty value, or it contains a quote or newline.');
|
|
309
|
+
setSecret(p.secrets, key, v);
|
|
310
|
+
return log.ok(`${key} saved in ${p.secrets} (mode 600). MCP servers started from now on get it (agent sessions never do).`);
|
|
311
|
+
}
|
|
312
|
+
if (sub === 'rm') { setSecret(p.secrets, rest[0], null); return log.ok(`${rest[0]} removed`); }
|
|
313
|
+
const keys = fs.existsSync(p.secrets) ? Object.keys((await import('./config.js')).parseEnv(fs.readFileSync(p.secrets, 'utf8'))) : [];
|
|
314
|
+
return console.log(keys.join('\n') || '(none)');
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
case 'ngrok': {
|
|
318
|
+
const ctx = loadContext(env);
|
|
319
|
+
const p = ctx.paths;
|
|
320
|
+
if (sub === 'token') {
|
|
321
|
+
const t = env.NGROK_AUTHTOKEN || (await readSecret('ngrok authtoken (dashboard.ngrok.com → Your Authtoken): '));
|
|
322
|
+
if (!/^[A-Za-z0-9_-]{20,}$/.test(t)) throw new Error('That does not look like an ngrok authtoken.');
|
|
323
|
+
writeFile(p.ngrokToken, t + '\n', { mode: 0o600 });
|
|
324
|
+
return log.ok('ngrok authtoken saved. Open tunnels with: harness-device ngrok up viewers');
|
|
325
|
+
}
|
|
326
|
+
if (sub === 'up') {
|
|
327
|
+
if (!ctx.caps.some((c) => c.id === 'ngrok')) throw new Error('Turn on the ngrok capability first: harness-device init --with ngrok && harness-device install');
|
|
328
|
+
if (!fs.existsSync(p.ngrokToken)) throw new Error('No authtoken yet: harness-device ngrok token');
|
|
329
|
+
// A password generated at load time must be saved, or the next run makes another.
|
|
330
|
+
if (!/^NGROK_VIEWER_PASS=/m.test(fs.existsSync(p.config) ? fs.readFileSync(p.config, 'utf8') : '')) saveConfig(ctx.cfg, env);
|
|
331
|
+
const names = ngrok.selectTunnels(ctx.cfg, rest.length ? rest : ['viewers'], ctx.platform.id);
|
|
332
|
+
writeFile(p.ngrokYml, ngrok.renderNgrokYml(ctx.cfg, fs.readFileSync(p.ngrokToken, 'utf8').trim(), ctx.platform.id), { mode: 0o600 });
|
|
333
|
+
writeFile(p.ngrokEnv, ngrok.renderNgrokEnv(names), { mode: 0o600 });
|
|
334
|
+
ctx.platform.ngrokUp(ctx);
|
|
335
|
+
await new Promise((r) => setTimeout(r, 4000));
|
|
336
|
+
const s = await device.ngrokStatus();
|
|
337
|
+
for (const t of s.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
|
|
338
|
+
if (names.some((n) => ['novnc', 'ttyd', 'pwui'].includes(n))) log.info(color.dim(` viewer login: ${ctx.cfg.NGROK_VIEWER_USER} / (NGROK_VIEWER_PASS in ${p.config})`));
|
|
339
|
+
return log.ok(s.running ? `ngrok up (survives reboots until: harness-device ngrok down)` : 'ngrok did not start yet; check: harness-device logs ngrok');
|
|
340
|
+
}
|
|
341
|
+
if (sub === 'down') {
|
|
342
|
+
ctx.platform.ngrokDown(ctx);
|
|
343
|
+
return log.ok('ngrok tunnels closed.');
|
|
344
|
+
}
|
|
345
|
+
const s = await device.ngrokStatus();
|
|
346
|
+
if (!s.running) return console.log('ngrok is not running (harness-device ngrok up <group>)');
|
|
347
|
+
for (const t of s.tunnels) console.log(`${t.name}\t${t.url}\t${t.addr}`);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
case 'restart': {
|
|
352
|
+
if (!sub) throw new Error('usage: restart <service>');
|
|
353
|
+
const ctx = loadContext(env);
|
|
354
|
+
const tmux = device.isTmux(sub);
|
|
355
|
+
if (tmux && process.env.TMUX_PANE && !f.force) throw new Error('This shell runs inside the harness tmux session: restarting tmux would end it, and every Remote Control session. Run it from a plain SSH shell, or add --force.');
|
|
356
|
+
const r = device.restartService(ctx, sub, { allowTmux: tmux });
|
|
357
|
+
return r.restarted ? log.ok(`${r.service}: ${r.state}`) : log.err(`${r.service} did not restart (state: ${r.state}); see harness-device logs ${r.service}`);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
case 'mcp': {
|
|
361
|
+
const { serve } = await import('./mcp/server.js');
|
|
362
|
+
return serve(env);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
case 'fleet': {
|
|
366
|
+
const file = getPaths(env).fleet;
|
|
367
|
+
if (sub === 'add') { fleet.addDevice(file, rest[0], rest[1]); return log.ok(`Added ${rest[0]} (${rest[1]}). Set it up: harness-device fleet run ${rest[0]} init --device ${rest[0]} --project app:/path && harness-device fleet run ${rest[0]} install`); }
|
|
368
|
+
if (sub === 'rm') { fleet.removeDevice(file, rest[0]); return log.ok(`Removed ${rest[0]}`); }
|
|
369
|
+
if (sub === 'list') { for (const d of fleet.readFleet(file)) console.log(`${d.name}\t${d.host}`); return; }
|
|
370
|
+
if (sub === 'run') {
|
|
371
|
+
if (!rest[0]) throw new Error('usage: fleet run <device> <harness-device args...>');
|
|
372
|
+
process.exitCode = fleet.fleetRun(file, rest[0], rest.slice(1));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
await fleet.fleetStatus(file);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
default:
|
|
380
|
+
throw new Error(`Unknown command "${cmd}". Run: harness-device help`);
|
|
381
|
+
}
|
|
382
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Config lives in ~/.harness-device/config.env (KEY=value lines, # comments).
|
|
2
|
+
// Node is the only reader of config.env; the shell scripts read the generated
|
|
3
|
+
// runtime.env (HD_* shell variables) and projects.tsv instead.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_CAPABILITIES = 'browser,playwright,display,shell,system,sqlite,docker,graphify';
|
|
11
|
+
export const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
|
|
12
|
+
|
|
13
|
+
export function hdHome(env = process.env) {
|
|
14
|
+
return env.HARNESS_DEVICE_HOME || path.join(env.HOME || os.homedir(), '.harness-device');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function paths(env = process.env) {
|
|
18
|
+
const home = hdHome(env);
|
|
19
|
+
return {
|
|
20
|
+
home,
|
|
21
|
+
config: path.join(home, 'config.env'),
|
|
22
|
+
runtimeEnv: path.join(home, 'runtime.env'),
|
|
23
|
+
projects: path.join(home, 'projects.tsv'),
|
|
24
|
+
secrets: path.join(home, 'secrets.env'),
|
|
25
|
+
ngrokYml: path.join(home, 'ngrok.yml'),
|
|
26
|
+
ngrokToken: path.join(home, 'ngrok-authtoken'),
|
|
27
|
+
bin: path.join(home, 'bin'),
|
|
28
|
+
pkg: path.join(home, 'pkg'),
|
|
29
|
+
fleet: path.join(home, 'fleet.tsv'),
|
|
30
|
+
ngrokEnv: path.join(home, 'ngrok.env'),
|
|
31
|
+
state: path.join(home, 'state'),
|
|
32
|
+
logs: path.join(home, 'logs'),
|
|
33
|
+
profile: path.join(home, 'chromium-profile'),
|
|
34
|
+
units: path.join(env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), '.config'), 'systemd', 'user'),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function defaults(env = process.env) {
|
|
39
|
+
return {
|
|
40
|
+
SESSION: 'harness',
|
|
41
|
+
DEVICE: (os.hostname().split('.')[0] || 'device').replace(/[^A-Za-z0-9_-]/g, '-'),
|
|
42
|
+
PROVIDER: 'claude',
|
|
43
|
+
// conversation: each project slot is pinned to one conversation id and resumed
|
|
44
|
+
// after any restart or downtime. server: `claude remote-control` (on-demand
|
|
45
|
+
// sessions, restored by Claude Code only within ~4h).
|
|
46
|
+
SERVE_MODE: 'conversation',
|
|
47
|
+
// Keep agent transcripts this long (they are what restores are made from).
|
|
48
|
+
TRANSCRIPT_DAYS: '365',
|
|
49
|
+
DISPLAY_NUM: '99',
|
|
50
|
+
SCREEN: '1920x1080x24',
|
|
51
|
+
CDP_PORT: '9222',
|
|
52
|
+
VNC_PORT: '5900',
|
|
53
|
+
NOVNC_PORT: '6080',
|
|
54
|
+
TTYD_PORT: '7681',
|
|
55
|
+
PW_UI_PORT: '9323',
|
|
56
|
+
HEAL_INTERVAL: '2min',
|
|
57
|
+
CAPABILITIES: DEFAULT_CAPABILITIES,
|
|
58
|
+
OLLAMA_MODELS: '',
|
|
59
|
+
NGROK_VIEWER_USER: 'harness',
|
|
60
|
+
NGROK_VIEWER_PASS: crypto.randomBytes(15).toString('base64url'),
|
|
61
|
+
NGROK_APP_PORTS: '',
|
|
62
|
+
NGROK_APPS_PUBLIC: '0',
|
|
63
|
+
NGROK_DOMAIN: '',
|
|
64
|
+
// Your existing Dokploy (e.g. https://dokploy.example.com); the device only uses its API.
|
|
65
|
+
DOKPLOY_URL: '',
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Parse KEY=value text. Strips full-line and inline ` #` comments, and matching quotes. */
|
|
70
|
+
export function parseEnv(text) {
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
73
|
+
const line = raw.trim();
|
|
74
|
+
if (!line || line.startsWith('#')) continue;
|
|
75
|
+
const eq = line.indexOf('=');
|
|
76
|
+
if (eq < 1) continue;
|
|
77
|
+
const key = line.slice(0, eq).trim();
|
|
78
|
+
let val = line.slice(eq + 1).trim();
|
|
79
|
+
const q = val[0];
|
|
80
|
+
if ((q === '"' || q === "'") && val.indexOf(q, 1) > 0) {
|
|
81
|
+
val = val.slice(1, val.indexOf(q, 1));
|
|
82
|
+
} else {
|
|
83
|
+
const hash = val.search(/\s#/);
|
|
84
|
+
if (hash >= 0) val = val.slice(0, hash).trim();
|
|
85
|
+
}
|
|
86
|
+
out[key] = val;
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function quoteEnv(v) {
|
|
92
|
+
return /^[A-Za-z0-9_./:,@%+=-]*$/.test(v) ? v : `"${String(v).replace(/"/g, '')}"`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function serializeConfig(cfg) {
|
|
96
|
+
const lines = [
|
|
97
|
+
'# @dreamtree-org/harness-device config. Edit, then run: harness-device install',
|
|
98
|
+
'# Projects: PROJECT_<name>=/absolute/path (each gets a persistent agent session that survives reboots)',
|
|
99
|
+
'',
|
|
100
|
+
];
|
|
101
|
+
const projectKeys = Object.keys(cfg).filter((k) => k.startsWith('PROJECT_')).sort();
|
|
102
|
+
const mcpKeys = Object.keys(cfg).filter((k) => k.startsWith('MCP_')).sort();
|
|
103
|
+
const rest = Object.keys(cfg).filter((k) => !k.startsWith('PROJECT_') && !k.startsWith('MCP_'));
|
|
104
|
+
for (const k of rest) lines.push(`${k}=${quoteEnv(cfg[k])}`);
|
|
105
|
+
lines.push('', '# Projects');
|
|
106
|
+
for (const k of projectKeys) lines.push(`${k}=${quoteEnv(cfg[k])}`);
|
|
107
|
+
lines.push('', '# Extra MCP servers registered for Claude at user scope: MCP_<name>=command args');
|
|
108
|
+
lines.push('# MCP_context7=npx -y @upstash/context7-mcp');
|
|
109
|
+
for (const k of mcpKeys) lines.push(`${k}=${quoteEnv(cfg[k])}`);
|
|
110
|
+
return lines.join('\n') + '\n';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function loadConfig(env = process.env) {
|
|
114
|
+
const p = paths(env);
|
|
115
|
+
const file = fs.existsSync(p.config) ? parseEnv(fs.readFileSync(p.config, 'utf8')) : null;
|
|
116
|
+
return { exists: !!file, cfg: { ...defaults(env), ...(file || {}) } };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function saveConfig(cfg, env = process.env) {
|
|
120
|
+
const p = paths(env);
|
|
121
|
+
fs.mkdirSync(p.home, { recursive: true, mode: 0o700 });
|
|
122
|
+
fs.writeFileSync(p.config, serializeConfig(cfg), { mode: 0o600 });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function projects(cfg) {
|
|
126
|
+
return Object.keys(cfg)
|
|
127
|
+
.filter((k) => k.startsWith('PROJECT_'))
|
|
128
|
+
.map((k) => ({ name: k.slice(8), dir: cfg[k] }))
|
|
129
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function mcpServers(cfg) {
|
|
133
|
+
return Object.keys(cfg)
|
|
134
|
+
.filter((k) => k.startsWith('MCP_') && cfg[k])
|
|
135
|
+
.map((k) => ({ name: k.slice(4), command: cfg[k] }));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function capabilityIds(cfg) {
|
|
139
|
+
return String(cfg.CAPABILITIES || '')
|
|
140
|
+
.split(',')
|
|
141
|
+
.map((s) => s.trim())
|
|
142
|
+
.filter(Boolean);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Parse "name:/path" (or a bare path, name = basename). */
|
|
146
|
+
export function parseProjectSpec(spec, env = process.env) {
|
|
147
|
+
const m = /^([^:/]+):(.+)$/.exec(spec);
|
|
148
|
+
const dir = path.resolve(m ? m[2] : spec);
|
|
149
|
+
const name = m ? m[1] : path.basename(dir);
|
|
150
|
+
return validateProject({ name, dir }, env);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function validateProject({ name, dir }, env = process.env) {
|
|
154
|
+
if (!NAME_RE.test(name)) throw new Error(`Project name "${name}" must be letters, digits, _ or - (max 40).`);
|
|
155
|
+
if (!path.isAbsolute(dir)) throw new Error(`Project "${name}": path must be absolute (${dir}).`);
|
|
156
|
+
if (/['"\t\n\\$`]/.test(dir)) throw new Error(`Project "${name}": path contains quotes, tabs or other unsafe characters.`);
|
|
157
|
+
const home = path.resolve(env.HOME || os.homedir());
|
|
158
|
+
if (path.resolve(dir) === home) throw new Error(`Project "${name}": the home directory itself can't be a project; use a subfolder.`);
|
|
159
|
+
if (path.resolve(dir) === '/') throw new Error(`Project "${name}": "/" can't be a project.`);
|
|
160
|
+
return { name, dir };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Problems that make the config unusable; returns a list of messages. */
|
|
164
|
+
export function validateConfig(cfg, env = process.env) {
|
|
165
|
+
const errs = [];
|
|
166
|
+
for (const p of projects(cfg)) {
|
|
167
|
+
try { validateProject(p, env); } catch (e) { errs.push(e.message); }
|
|
168
|
+
}
|
|
169
|
+
if (!/^[a-z]+$/.test(String(cfg.PROVIDER))) errs.push('PROVIDER must be a provider id such as claude.');
|
|
170
|
+
if (!['conversation', 'server'].includes(cfg.SERVE_MODE)) errs.push('SERVE_MODE must be conversation or server.');
|
|
171
|
+
if (!/^\d+$/.test(String(cfg.TRANSCRIPT_DAYS)) || Number(cfg.TRANSCRIPT_DAYS) < 30) errs.push('TRANSCRIPT_DAYS must be a number of days, at least 30.');
|
|
172
|
+
if (cfg.DOKPLOY_URL && !/^https?:\/\/[^\s'"]+$/.test(cfg.DOKPLOY_URL)) errs.push('DOKPLOY_URL must be an http(s) URL.');
|
|
173
|
+
for (const k of ['DISPLAY_NUM', 'CDP_PORT', 'VNC_PORT', 'NOVNC_PORT', 'TTYD_PORT', 'PW_UI_PORT']) {
|
|
174
|
+
if (!/^\d+$/.test(String(cfg[k]))) errs.push(`${k} must be a number (got "${cfg[k]}").`);
|
|
175
|
+
}
|
|
176
|
+
if (!NAME_RE.test(cfg.SESSION)) errs.push('SESSION must be letters, digits, _ or -.');
|
|
177
|
+
if (!NAME_RE.test(cfg.DEVICE)) errs.push('DEVICE must be letters, digits, _ or - (max 40).');
|
|
178
|
+
if (String(cfg.NGROK_APP_PORTS).trim() && !/^\d+(,\d+)*$/.test(String(cfg.NGROK_APP_PORTS).replace(/\s/g, ''))) {
|
|
179
|
+
errs.push('NGROK_APP_PORTS must be a comma-separated list of ports.');
|
|
180
|
+
}
|
|
181
|
+
const pass = String(cfg.NGROK_VIEWER_PASS || '');
|
|
182
|
+
if (pass.length < 8 || pass.length > 128 || /[:\s"]/.test(pass)) errs.push('NGROK_VIEWER_PASS must be 8-128 characters with no colon, space or quote.');
|
|
183
|
+
if (!/^[A-Za-z0-9_-]+$/.test(String(cfg.NGROK_VIEWER_USER))) errs.push('NGROK_VIEWER_USER must be letters, digits, _ or -.');
|
|
184
|
+
for (const s of mcpServers(cfg)) if (!NAME_RE.test(s.name)) errs.push(`MCP server name "${s.name}" is invalid.`);
|
|
185
|
+
return errs;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Single quotes mean the same thing to bash `source` and to systemd's
|
|
189
|
+
// EnvironmentFile parser, as long as the value itself holds no quote or newline.
|
|
190
|
+
function shq(v) {
|
|
191
|
+
const s = String(v);
|
|
192
|
+
if (/['\n]/.test(s)) throw new Error(`Value can't contain a single quote or newline: ${s}`);
|
|
193
|
+
return `'${s}'`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** runtime.env: what the shell scripts and systemd units read. */
|
|
197
|
+
export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformId = 'linux' } = {}) {
|
|
198
|
+
const p = paths(env);
|
|
199
|
+
const vars = {
|
|
200
|
+
HD_HOME: p.home,
|
|
201
|
+
// So `harness-device` run inside a session (and its MCP server) finds this
|
|
202
|
+
// device, and the served agent uses the same Claude config the installer wired.
|
|
203
|
+
HARNESS_DEVICE_HOME: p.home,
|
|
204
|
+
...(env.CLAUDE_CONFIG_DIR ? { CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR } : {}),
|
|
205
|
+
HD_SESSION: cfg.SESSION,
|
|
206
|
+
HD_DEVICE: cfg.DEVICE,
|
|
207
|
+
HD_PROVIDER: cfg.PROVIDER,
|
|
208
|
+
HD_SERVE_MODE: cfg.SERVE_MODE,
|
|
209
|
+
HD_DISPLAY_NUM: cfg.DISPLAY_NUM,
|
|
210
|
+
HD_SCREEN: cfg.SCREEN,
|
|
211
|
+
HD_CDP_PORT: cfg.CDP_PORT,
|
|
212
|
+
HD_VNC_PORT: cfg.VNC_PORT,
|
|
213
|
+
HD_NOVNC_PORT: cfg.NOVNC_PORT,
|
|
214
|
+
HD_TTYD_PORT: cfg.TTYD_PORT,
|
|
215
|
+
HD_PW_UI_PORT: cfg.PW_UI_PORT,
|
|
216
|
+
HD_PROFILE: p.profile,
|
|
217
|
+
HD_UNITS: units.join(' '),
|
|
218
|
+
HD_PLATFORM: platformId,
|
|
219
|
+
// Linux: the virtual display. macOS: the real screen, no DISPLAY.
|
|
220
|
+
...(platformId === 'linux' ? { DISPLAY: `:${cfg.DISPLAY_NUM}` } : {}),
|
|
221
|
+
// Services start with a bare PATH; keep the one the installer ran with, so
|
|
222
|
+
// `claude`, `node`, `npx`, nvm/volta and Homebrew installs resolve the same way.
|
|
223
|
+
PATH: [...new Set([p.bin, path.join(p.pkg, 'node_modules', '.bin'), path.join(env.HOME || os.homedir(), '.local', 'bin'),
|
|
224
|
+
...(platformId === 'darwin' ? ['/opt/homebrew/bin', '/usr/local/bin'] : []),
|
|
225
|
+
...String(env.PATH || '/usr/local/bin:/usr/bin:/bin').split(':')])].filter(Boolean).join(':'),
|
|
226
|
+
TERM: 'xterm-256color',
|
|
227
|
+
LANG: env.LANG || 'C.UTF-8',
|
|
228
|
+
};
|
|
229
|
+
// systemd EnvironmentFile and bash `source` both accept KEY='value'.
|
|
230
|
+
return (
|
|
231
|
+
'# Generated by harness-device install. Do not edit; edit config.env instead.\n' +
|
|
232
|
+
Object.entries(vars).map(([k, v]) => `${k}=${shq(v)}`).join('\n') +
|
|
233
|
+
'\n'
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
export function renderProjectsTsv(cfg) {
|
|
238
|
+
return projects(cfg).map((p) => `${p.name}\t${p.dir}`).join('\n') + (projects(cfg).length ? '\n' : '');
|
|
239
|
+
}
|
package/src/context.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
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
|
+
/** Everything a command needs to know about this device. */
|
|
24
|
+
export function loadContext(rawEnv = process.env, { dryRun = false } = {}) {
|
|
25
|
+
const plat = detectPlatform(rawEnv);
|
|
26
|
+
const env = plat.userEnv(rawEnv);
|
|
27
|
+
const { cfg, exists } = loadConfig(env);
|
|
28
|
+
const caps = resolveCapabilities(capabilityIds(cfg));
|
|
29
|
+
return {
|
|
30
|
+
env,
|
|
31
|
+
dryRun,
|
|
32
|
+
exists,
|
|
33
|
+
cfg,
|
|
34
|
+
platform: plat,
|
|
35
|
+
paths: { ...paths(env), units: plat.serviceDir(env) },
|
|
36
|
+
caps,
|
|
37
|
+
units: unitsFor(caps, plat.id),
|
|
38
|
+
projects: projects(cfg),
|
|
39
|
+
secrets: readSecrets(paths(env).secrets),
|
|
40
|
+
provider: provider(cfg.PROVIDER),
|
|
41
|
+
warn: (m) => console.log(`! ${m}`),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The MCP servers the provider registers: each capability's, the device's own, and MCP_* from config. */
|
|
46
|
+
export function allMcpServers(ctx) {
|
|
47
|
+
const list = ctx.caps.flatMap((c) => (c.mcp ? c.mcp(ctx.cfg, ctx.paths) : []));
|
|
48
|
+
list.push({ name: 'harness-device', command: `${ctx.paths.bin}/harness-device`, args: ['mcp'] });
|
|
49
|
+
for (const s of mcpServers(ctx.cfg)) {
|
|
50
|
+
const [command, ...args] = s.command.split(/\s+/).filter(Boolean);
|
|
51
|
+
list.push({ name: s.name, command: `${ctx.paths.bin}/hd-with-secrets`, args: [command, ...args] });
|
|
52
|
+
}
|
|
53
|
+
return list;
|
|
54
|
+
}
|