@dreamtree-org/harness-device 0.2.0 → 0.3.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/README.md +17 -0
- package/package.json +1 -1
- package/src/apps.js +90 -0
- package/src/capabilities.js +9 -1
- package/src/cli.js +41 -4
- package/src/config.js +3 -0
- package/src/jobs.js +141 -0
- package/src/mcp/server.js +69 -0
- package/src/project.js +248 -0
- package/src/providers/claude.js +2 -1
- package/src/serve/scopes.js +5 -2
- package/src/stack.js +67 -0
package/README.md
CHANGED
|
@@ -193,6 +193,22 @@ Disk running out? `harness-device cleanup`, or the `disk_cleanup` tool, lists wh
|
|
|
193
193
|
3. Run `install`.
|
|
194
194
|
4. Add `https://mcp.example.com/mcp` to your MCP client.
|
|
195
195
|
|
|
196
|
+
### Managed apps (clone, set up, run, update)
|
|
197
|
+
|
|
198
|
+
Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike projects, they get no agent session unless asked.
|
|
199
|
+
|
|
200
|
+
| Tool (CLI) | |
|
|
201
|
+
| --- | --- |
|
|
202
|
+
| `git_clone` (`app clone <url>`) | Clones the repo and detects its stack, as a job. Private GitHub repos use the device secret `GITHUB_TOKEN`, passed to git through the environment only |
|
|
203
|
+
| `project_setup` (`app setup`) | Detects node (npm, pnpm or yarn by lockfile), python (uv, poetry or pip), go, ruby, php or docker compose, then installs and builds, as a job |
|
|
204
|
+
| `project_start` / `project_stop` | Runs the app as a long-running process with its `.env` and `PORT`. It's restarted on crash and reboot and held to the safe maximums |
|
|
205
|
+
| `project_deploy` (`app deploy`) | Pull (fast-forward only), install, build, then restart if running, as one job. GitHub push webhooks run it |
|
|
206
|
+
| `git_pull` | Updates only. It refuses when there are uncommitted changes |
|
|
207
|
+
| `file_read` / `file_write` | Inside the app folder only; `.git` and `.env` are off limits |
|
|
208
|
+
| `env_manage` | The app's `.env`. `list` shows names only. `set` takes a value or `from_secret` (copies a device secret without exposing it), and asks first |
|
|
209
|
+
| `shell_exec` (`app exec <app> -- <cmd>`) | One command in the app folder: up to 120s inline, otherwise as a job. Through the pool it needs `device:admin` |
|
|
210
|
+
| `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
|
|
211
|
+
|
|
196
212
|
### Join a pool (HarnessPro)
|
|
197
213
|
|
|
198
214
|
`harness-device join <hub> --enroll <secret>` adds this device to a HarnessPro pool. You don't type it yourself: the dashboard's **Connect a device** gives a one-time `curl … | bash` command that installs harness-device and runs it.
|
|
@@ -201,6 +217,7 @@ Disk running out? `harness-device cleanup`, or the `disk_cleanup` tool, lists wh
|
|
|
201
217
|
- **What the pool may do:** `POOL_SCOPES` in config.env sets it (default `device:read,device:operate`). It's set on the machine only, and the hub can never raise it.
|
|
202
218
|
- **Shared secrets and settings from the hub:** they never overwrite a secret you set locally, and never names such as `ANTHROPIC_*` or `SERVE_OWNER_PASSWORD`.
|
|
203
219
|
- **Leaving:** `harness-device leave`, or Disconnect in the dashboard.
|
|
220
|
+
- **As root on a server:** the dashboard's install command creates a dedicated user (`harness`, or `HD_USER=name`), installs the system packages as root, and runs harness-device as that user with no sudo. `harness-device install --system-steps` prints what that system step runs for a user.
|
|
204
221
|
|
|
205
222
|
**As a Dokploy app** (no host install): deploy `docker-compose.dokploy.yml` as a Compose app. Its comments list the environment variables and the domain. It serves a reduced set of tools: `resources`, `docker_summary`, `docker_limit` and `disk_cleanup` (Docker items), for the host's Docker, RAM, CPU and disk. Sessions, processes and the browser need the host install. The image is also built to `ghcr.io/dreamtree-org/harness-device` by `.github/workflows/image.yml`.
|
|
206
223
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreamtree-org/harness-device",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Partha Preetham Krishna",
|
package/src/apps.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Managed projects ("apps"): repositories cloned and run by the project tools.
|
|
2
|
+
// Each lives in APPS_DIR/<name> (default ~/apps) and has a record in
|
|
3
|
+
// state/apps/<name>.json. Apps get no agent session unless asked (session:true
|
|
4
|
+
// registers them as a PROJECT_ as well).
|
|
5
|
+
//
|
|
6
|
+
// Every file path a tool takes goes through resolveIn(): it must stay inside
|
|
7
|
+
// the app's folder after resolving symlinks, and never touch .git or the
|
|
8
|
+
// .env files (env_manage handles those).
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
export const APP_NAME = /^[a-z0-9][a-z0-9_-]{0,39}$/;
|
|
15
|
+
|
|
16
|
+
export function appsDir(ctx) {
|
|
17
|
+
return path.resolve(ctx.cfg.APPS_DIR || path.join(ctx.env.HOME || os.homedir(), 'apps'));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const recDir = (ctx) => path.join(ctx.paths.state, 'apps');
|
|
21
|
+
const recFile = (ctx, name) => path.join(recDir(ctx), `${name}.json`);
|
|
22
|
+
|
|
23
|
+
export function listApps(ctx) {
|
|
24
|
+
const d = recDir(ctx);
|
|
25
|
+
if (!fs.existsSync(d)) return [];
|
|
26
|
+
return fs.readdirSync(d).filter((f) => f.endsWith('.json')).map((f) => {
|
|
27
|
+
try { return JSON.parse(fs.readFileSync(path.join(d, f), 'utf8')); } catch { return null; }
|
|
28
|
+
}).filter(Boolean).sort((a, b) => a.name.localeCompare(b.name));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function getApp(ctx, name) {
|
|
32
|
+
if (!APP_NAME.test(String(name || ''))) throw new Error(`Not an app name: ${name}`);
|
|
33
|
+
const f = recFile(ctx, name);
|
|
34
|
+
if (!fs.existsSync(f)) {
|
|
35
|
+
// A session project (PROJECT_*) can be used as an app too, without cloning.
|
|
36
|
+
const p = ctx.projects.find((x) => x.name === name);
|
|
37
|
+
if (p) return { name, dir: p.dir, project: true };
|
|
38
|
+
throw new Error(`No app "${name}". Apps: ${listApps(ctx).map((a) => a.name).join(', ') || 'none (git_clone one)'}`);
|
|
39
|
+
}
|
|
40
|
+
return JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function saveApp(ctx, app) {
|
|
44
|
+
fs.mkdirSync(recDir(ctx), { recursive: true });
|
|
45
|
+
const tmp = `${recFile(ctx, app.name)}.${process.pid}.tmp`;
|
|
46
|
+
fs.writeFileSync(tmp, JSON.stringify(app, null, 2));
|
|
47
|
+
fs.renameSync(tmp, recFile(ctx, app.name));
|
|
48
|
+
return app;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** A name from a repo URL: github.com/acme/My.App.git → my-app. */
|
|
52
|
+
export function nameFromUrl(url) {
|
|
53
|
+
const base = String(url).replace(/\/+$/, '').split(/[/:]/).pop().replace(/\.git$/, '');
|
|
54
|
+
return base.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Only https, ssh-style git@host:owner/repo, and file:// (tests, local mirrors). */
|
|
58
|
+
export function checkRepoUrl(url) {
|
|
59
|
+
const s = String(url || '');
|
|
60
|
+
if (/^https:\/\/[A-Za-z0-9.-]+\/[\w.~/-]+$/.test(s) || /^git@[A-Za-z0-9.-]+:[\w.~/-]+$/.test(s) || /^file:\/\/\/[\w.~/-]+$/.test(s)) return s;
|
|
61
|
+
throw new Error(`Not a repository URL I can clone: ${s} (use https://host/owner/repo, git@host:owner/repo, or file:///path)`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const DENY = [/^\.git(\/|$)/, /(^|\/)\.git(\/|$)/, /(^|\/)\.env(\..*)?$/];
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The absolute path of `rel` inside the app, or a thrown error. The deepest
|
|
68
|
+
* existing ancestor is resolved with realpath, so a symlink can't lead out.
|
|
69
|
+
*/
|
|
70
|
+
export function resolveIn(app, rel, { allowEnv = false } = {}) {
|
|
71
|
+
const r = String(rel || '').replace(/\\/g, '/');
|
|
72
|
+
if (!r || path.isAbsolute(r) || r.split('/').includes('..')) throw new Error(`Give a path inside the app, like src/index.js (got "${rel}")`);
|
|
73
|
+
const norm = path.posix.normalize(r);
|
|
74
|
+
if (DENY.some((re) => re.test(norm) && !(allowEnv && /\.env/.test(norm) && !/\.git/.test(norm)))) {
|
|
75
|
+
throw new Error(/\.env/.test(norm) ? `${norm}: use env_manage for .env files (values are never shown)` : `${norm}: .git is off limits`);
|
|
76
|
+
}
|
|
77
|
+
const root = fs.realpathSync(app.dir);
|
|
78
|
+
const target = path.join(root, norm);
|
|
79
|
+
let probe = target;
|
|
80
|
+
while (!fs.existsSync(probe)) probe = path.dirname(probe);
|
|
81
|
+
const real = fs.realpathSync(probe);
|
|
82
|
+
if (real !== root && !real.startsWith(root + path.sep)) throw new Error(`${norm} leads outside the app folder`);
|
|
83
|
+
if (fs.existsSync(target)) {
|
|
84
|
+
const rt = fs.realpathSync(target);
|
|
85
|
+
if (rt !== root && !rt.startsWith(root + path.sep)) throw new Error(`${norm} leads outside the app folder`);
|
|
86
|
+
}
|
|
87
|
+
return target;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const procName = (app) => `app-${app.name}`.slice(0, 40);
|
package/src/capabilities.js
CHANGED
|
@@ -106,7 +106,15 @@ harness-device upgrades itself from npm (AUTO_UPGRADE, default minor) without st
|
|
|
106
106
|
'Bash(launchctl list:*)', 'Bash(top -bn1:*)', 'Bash(top -l 1:*)',
|
|
107
107
|
],
|
|
108
108
|
checks: () => [],
|
|
109
|
-
docs: (cfg, plat) => `##
|
|
109
|
+
docs: (cfg, plat) => `## Managed apps (clone, set up, run, update)
|
|
110
|
+
Apps are repositories this device runs, in \`${cfg.APPS_DIR || '~/apps'}\`; unlike projects they get no agent session unless asked.
|
|
111
|
+
- \`git_clone\` (job) → \`project_setup\` (detects the stack, installs and builds; job) → \`project_start\` (a long-running process with the app's .env and PORT; restarted on crash and reboot, held to the safe maximums). \`project_stop\` stops it; \`project_deploy\` pulls, rebuilds and restarts in one job; \`git_pull\` only updates.
|
|
112
|
+
- Jobs run in the background: follow them with \`job_status\`, don't wait in a loop without telling the user.
|
|
113
|
+
- Files: \`file_read\` / \`file_write\` inside the app folder only; .git and .env are off limits. Environment: \`env_manage\` (names only; \`from_secret\` copies a device secret without you seeing it). Never put secrets in files or commands.
|
|
114
|
+
- \`shell_exec\` runs one command in an app folder; through the pool it needs device:admin.
|
|
115
|
+
- Private GitHub repos use the device secret GITHUB_TOKEN; if it is missing, ask the user to set it (on the machine, or as a pool secret), never for the token itself.
|
|
116
|
+
|
|
117
|
+
## Device, disk and services
|
|
110
118
|
- Overview: \`harness-device status\` (or the \`device_status\` / \`disk_usage\` MCP tools).
|
|
111
119
|
- Disk: \`df -h\`, \`du -sh <dir>\`. ${isMac(plat)
|
|
112
120
|
? 'This is macOS: memory `vm_stat`, ports `lsof -iTCP -sTCP:LISTEN -n -P`, processes `top -l 1 | head -30`. Harness services are launchd agents (`launchctl list | grep harness-device`); their logs are `harness-device logs <service>`.'
|
package/src/cli.js
CHANGED
|
@@ -4,7 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import readline from 'node:readline';
|
|
5
5
|
import { spawnSync } from 'node:child_process';
|
|
6
6
|
import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths, SETTABLE_KEYS, setConfigValue, setSecret } from './config.js';
|
|
7
|
-
import { ORDER, CAPABILITIES } from './capabilities.js';
|
|
7
|
+
import { ORDER, CAPABILITIES, systemStepsFor } from './capabilities.js';
|
|
8
8
|
import { loadContext } from './context.js';
|
|
9
9
|
import { install, uninstall } from './install.js';
|
|
10
10
|
import * as doctor from './doctor.js';
|
|
@@ -17,7 +17,7 @@ import * as resources from './resources.js';
|
|
|
17
17
|
import * as upgrader from './upgrade.js';
|
|
18
18
|
import * as cleanup from './cleanup.js';
|
|
19
19
|
import * as limits from './limits.js';
|
|
20
|
-
import { PKG, log, color, run, writeFile, capture } from './util.js';
|
|
20
|
+
import { PKG, PKG_ROOT, log, color, run, writeFile, capture, which } from './util.js';
|
|
21
21
|
|
|
22
22
|
const HELP = `${color.bold('harness-device')} ${PKG.version}: a reboot-proof dev device for remote AI agents (Claude Remote Control first)
|
|
23
23
|
|
|
@@ -25,6 +25,7 @@ ${color.bold('Set up')}
|
|
|
25
25
|
init [--device <name>] [--project name:/dir ...] [--with cap,...] [--without cap,...] [--serve-mode conversation|server]
|
|
26
26
|
[--dokploy-url https://your-dokploy]
|
|
27
27
|
install [--dry-run] [--skip-system] install or update everything (idempotent; never drops live sessions)
|
|
28
|
+
install --system-steps print, as JSON, the system step a root installer runs for this user (changes nothing)
|
|
28
29
|
doctor check everything, with fixes
|
|
29
30
|
uninstall [--purge]
|
|
30
31
|
|
|
@@ -56,6 +57,9 @@ ${color.bold('Device')}
|
|
|
56
57
|
join <hub-url> --enroll <secret> join a HarnessPro pool (the dashboard's install command runs this)
|
|
57
58
|
leave leave the pool and forget its credential
|
|
58
59
|
pool [status] pool hub, link state, POOL_SCOPES; \`pool link\` is the service
|
|
60
|
+
app list | clone <url> [--name N] [--branch B] | pull|setup|start|stop|deploy <app> | exec <app> -- <cmd>
|
|
61
|
+
managed apps in APPS_DIR (~/apps): clone, install, run, update (jobs run in the background)
|
|
62
|
+
job list | job <id> | job run <id> background jobs (clone, setup, deploy) and their logs
|
|
59
63
|
limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
|
|
60
64
|
cleanup [--apply] [item...] [--json] what could be freed safely (caches, build cache, old reports/logs); --apply removes it
|
|
61
65
|
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
@@ -76,8 +80,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
76
80
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
77
81
|
`;
|
|
78
82
|
|
|
79
|
-
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart', 'enforce', 'quiet'];
|
|
80
|
-
const VALUE_FLAGS = ['enroll', 'device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
83
|
+
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart', 'enforce', 'quiet', 'systemSteps', 'session'];
|
|
84
|
+
const VALUE_FLAGS = ['enroll', 'name', 'branch', 'command', 'tokenSecret', 'device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
81
85
|
|
|
82
86
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
83
87
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -203,6 +207,16 @@ export async function main(argv) {
|
|
|
203
207
|
|
|
204
208
|
case 'install': {
|
|
205
209
|
const ctx = loadContext(env, { dryRun: !!f.dryRun });
|
|
210
|
+
// For a root-run installer (HarnessPro's install command) that sets the
|
|
211
|
+
// device up for another user: what the system step would run, as JSON.
|
|
212
|
+
if (f.systemSteps) {
|
|
213
|
+
return console.log(JSON.stringify({
|
|
214
|
+
steps: systemStepsFor(ctx.caps).join(','),
|
|
215
|
+
setup: path.join(PKG_ROOT, 'sh', 'setup', `${ctx.platform.id}.sh`),
|
|
216
|
+
npx: which('npx', ctx.env) || 'npx',
|
|
217
|
+
user: env.USER || os.userInfo().username,
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
206
220
|
return install(ctx, { skipSystem: !!f.skipSystem, skipPkg: !!f.skipPkg, graceful: !!f.graceful });
|
|
207
221
|
}
|
|
208
222
|
|
|
@@ -309,6 +323,29 @@ export async function main(argv) {
|
|
|
309
323
|
return install(loadContext(env), { skipSystem: true, graceful: true });
|
|
310
324
|
}
|
|
311
325
|
|
|
326
|
+
case 'app':
|
|
327
|
+
case 'apps': {
|
|
328
|
+
const ctx = loadContext(env);
|
|
329
|
+
const pr = await import('./project.js');
|
|
330
|
+
const out = (v) => console.log(typeof v === 'string' ? v : JSON.stringify(v, null, 2));
|
|
331
|
+
if (!sub || sub === 'list') return out(pr.list(ctx));
|
|
332
|
+
if (sub === 'clone') return out(await pr.clone(ctx, { url: rest[0], name: f.name, branch: f.branch, tokenSecret: f.tokenSecret, session: !!f.session }));
|
|
333
|
+
if (['pull', 'setup', 'deploy'].includes(sub)) return out(await pr[sub](ctx, { app: rest[0] }));
|
|
334
|
+
if (sub === 'start') return out(pr.start(ctx, { app: rest[0], command: f.command, port: f.port }));
|
|
335
|
+
if (sub === 'stop') return out(pr.stop(ctx, { app: rest[0] }));
|
|
336
|
+
if (sub === 'exec') return out(await pr.shellExec(ctx, { app: rest[0], command: rest.slice(1).join(' '), timeoutSeconds: f.timeout }));
|
|
337
|
+
throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec');
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
case 'job':
|
|
341
|
+
case 'jobs': {
|
|
342
|
+
const ctx = loadContext(env);
|
|
343
|
+
const jobs = await import('./jobs.js');
|
|
344
|
+
if (sub === 'run') { const j = await jobs.runJob(ctx, rest[0]); process.exitCode = j.status === 'done' ? 0 : 1; return; }
|
|
345
|
+
if (!sub || sub === 'list') return console.log(JSON.stringify(jobs.listJobs(ctx), null, 2));
|
|
346
|
+
return console.log(JSON.stringify(jobs.describeJob(ctx, jobs.getJob(ctx, sub)), null, 2));
|
|
347
|
+
}
|
|
348
|
+
|
|
312
349
|
case 'cleanup': {
|
|
313
350
|
const ctx = loadContext(env);
|
|
314
351
|
const items = cleanup.plan(ctx);
|
package/src/config.js
CHANGED
|
@@ -98,6 +98,8 @@ export function defaults(env = process.env) {
|
|
|
98
98
|
// Pool (capability "pool", harness-device join): what the pool hub may do
|
|
99
99
|
// here. Set on the machine only; the hub can never raise it.
|
|
100
100
|
POOL_SCOPES: 'device:read,device:operate',
|
|
101
|
+
// Where git_clone puts managed apps (empty = ~/apps).
|
|
102
|
+
APPS_DIR: '',
|
|
101
103
|
};
|
|
102
104
|
}
|
|
103
105
|
|
|
@@ -210,6 +212,7 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
210
212
|
if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
|
|
211
213
|
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
212
214
|
errs.push(...limitsMod.validate(cfg));
|
|
215
|
+
if (cfg.APPS_DIR && (!path.isAbsolute(String(cfg.APPS_DIR)) || /['"\t\n\\$`]/.test(String(cfg.APPS_DIR)))) errs.push('APPS_DIR must be an absolute path without quotes or special characters.');
|
|
213
216
|
if (cfg.POOL_SCOPES !== undefined && !/^device:(read|operate|admin)(,device:(read|operate|admin))*$/.test(String(cfg.POOL_SCOPES).replace(/\s/g, ''))) errs.push('POOL_SCOPES must be a comma-separated list of device:read, device:operate, device:admin.');
|
|
214
217
|
if (!/^\d+$/.test(String(cfg.SERVE_PORT ?? '7700')) || Number(cfg.SERVE_PORT ?? 7700) < 1 || Number(cfg.SERVE_PORT ?? 7700) > 65535) errs.push('SERVE_PORT must be a port, 1-65535.');
|
|
215
218
|
if (cfg.SERVE_HOST !== undefined && !/^[A-Za-z0-9.:-]+$/.test(String(cfg.SERVE_HOST))) errs.push('SERVE_HOST must be an IP address or host name.');
|
package/src/jobs.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Background jobs: clone, setup, pull, deploy and long shell commands run
|
|
2
|
+
// detached (platform.spawnDetached → `harness-device job run <id>`), so a tool
|
|
3
|
+
// call returns at once with a job id; job_status reports progress and the log.
|
|
4
|
+
//
|
|
5
|
+
// A job is a list of steps, each a shell line and a folder, run in order with
|
|
6
|
+
// bash; the first failing step fails the job. Steps may be "@internal" names
|
|
7
|
+
// that this module runs in-process (saving the app after a clone, restarting
|
|
8
|
+
// its process). Secrets reach git only through the environment, never the
|
|
9
|
+
// command line, the job file or the log.
|
|
10
|
+
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import { readSecrets } from './context.js';
|
|
16
|
+
import { PKG_ROOT } from './util.js';
|
|
17
|
+
|
|
18
|
+
const KEEP = 50;
|
|
19
|
+
const dirOf = (ctx) => path.join(ctx.paths.state, 'jobs');
|
|
20
|
+
const fileOf = (ctx, id) => path.join(dirOf(ctx), `${id}.json`);
|
|
21
|
+
export const logOf = (ctx, id) => path.join(ctx.paths.logs, 'jobs', `${id}.log`);
|
|
22
|
+
|
|
23
|
+
function write(ctx, job) {
|
|
24
|
+
fs.mkdirSync(dirOf(ctx), { recursive: true });
|
|
25
|
+
const tmp = `${fileOf(ctx, job.id)}.${process.pid}.tmp`;
|
|
26
|
+
fs.writeFileSync(tmp, JSON.stringify(job, null, 2));
|
|
27
|
+
fs.renameSync(tmp, fileOf(ctx, job.id));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function getJob(ctx, id) {
|
|
31
|
+
if (!/^[a-z0-9-]{6,40}$/.test(String(id || ''))) throw new Error(`Not a job id: ${id}`);
|
|
32
|
+
const f = fileOf(ctx, id);
|
|
33
|
+
if (!fs.existsSync(f)) throw new Error(`No job ${id}`);
|
|
34
|
+
return JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function listJobs(ctx, n = 20) {
|
|
38
|
+
const d = dirOf(ctx);
|
|
39
|
+
if (!fs.existsSync(d)) return [];
|
|
40
|
+
return fs.readdirSync(d).filter((f) => f.endsWith('.json')).map((f) => { try { return JSON.parse(fs.readFileSync(path.join(d, f), 'utf8')); } catch { return null; } })
|
|
41
|
+
.filter(Boolean).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, n);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function prune(ctx) {
|
|
45
|
+
const all = listJobs(ctx, 10000);
|
|
46
|
+
for (const j of all.slice(KEEP)) {
|
|
47
|
+
fs.rmSync(fileOf(ctx, j.id), { force: true });
|
|
48
|
+
fs.rmSync(logOf(ctx, j.id), { force: true });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function tail(file, lines = 80) {
|
|
53
|
+
try {
|
|
54
|
+
const t = fs.readFileSync(file, 'utf8').split('\n');
|
|
55
|
+
return t.slice(-lines - 1).join('\n').trim();
|
|
56
|
+
} catch { return ''; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Create a job and start it detached. steps: [{ name, cmd, cwd } | { name, internal, args }].
|
|
61
|
+
* tokenSecret: the name of a device secret git may use for https://github.com.
|
|
62
|
+
* Returns the job.
|
|
63
|
+
*/
|
|
64
|
+
export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false }) {
|
|
65
|
+
const id = `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
|
|
66
|
+
const job = { id, kind, app, status: 'queued', step: null, steps: steps.map((s) => ({ name: s.name, cmd: s.cmd || null, cwd: s.cwd || null, internal: s.internal || null, args: s.args || null })), tokenSecret, exit: null, error: null, createdAt: new Date().toISOString(), startedAt: null, finishedAt: null };
|
|
67
|
+
write(ctx, job);
|
|
68
|
+
prune(ctx);
|
|
69
|
+
fs.mkdirSync(path.dirname(logOf(ctx, id)), { recursive: true });
|
|
70
|
+
if (inline || ctx.env.HD_JOBS_INLINE === '1') return runJob(ctx, id).then(() => getJob(ctx, id));
|
|
71
|
+
const bin = path.join(PKG_ROOT, 'bin', 'harness-device.js');
|
|
72
|
+
ctx.platform.spawnDetached(ctx, `job-${id}`, [process.execPath, bin, 'job', 'run', id], logOf(ctx, id));
|
|
73
|
+
return Promise.resolve(job);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Git auth through the environment only (GIT_CONFIG_*), for https://github.com. */
|
|
77
|
+
export function gitAuthEnv(token) {
|
|
78
|
+
if (!token) return {};
|
|
79
|
+
const basic = Buffer.from(`x-access-token:${token}`).toString('base64');
|
|
80
|
+
return { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'http.https://github.com/.extraheader', GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`, GIT_TERMINAL_PROMPT: '0' };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function runStep(cmd, cwd, env, log, redact) {
|
|
84
|
+
return new Promise((resolve) => {
|
|
85
|
+
const fd = fs.openSync(log, 'a');
|
|
86
|
+
const out = [];
|
|
87
|
+
const child = spawn('bash', ['-lc', cmd], { cwd, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
88
|
+
const pipe = (b) => { const s = redact(String(b)); out.push(s); fs.writeSync(fd, s); };
|
|
89
|
+
child.stdout.on('data', pipe);
|
|
90
|
+
child.stderr.on('data', pipe);
|
|
91
|
+
child.on('close', (code) => { fs.closeSync(fd); resolve(code ?? 1); });
|
|
92
|
+
child.on('error', (e) => { fs.writeSync(fd, `${e.message}\n`); fs.closeSync(fd); resolve(127); });
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** `harness-device job run <id>`: run the steps, record status. internals: { name: async (ctx, job, args) => void }. */
|
|
97
|
+
export async function runJob(ctx, id, internals = {}) {
|
|
98
|
+
const job = getJob(ctx, id);
|
|
99
|
+
const log = logOf(ctx, id);
|
|
100
|
+
const token = job.tokenSecret ? readSecrets(ctx.paths.secrets)[job.tokenSecret] || null : null;
|
|
101
|
+
const redact = (s) => (token ? s.split(token).join('***') : s);
|
|
102
|
+
const env = { ...ctx.env, ...gitAuthEnv(token), CI: '1' };
|
|
103
|
+
for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX']) delete env[k];
|
|
104
|
+
job.status = 'running';
|
|
105
|
+
job.startedAt = new Date().toISOString();
|
|
106
|
+
write(ctx, job);
|
|
107
|
+
const say = (m) => fs.appendFileSync(log, `\n[harness-device] ${m}\n`);
|
|
108
|
+
const builtins = { ...(await import('./project.js')).INTERNALS, ...internals };
|
|
109
|
+
try {
|
|
110
|
+
for (const [i, s] of job.steps.entries()) {
|
|
111
|
+
job.step = i;
|
|
112
|
+
write(ctx, job);
|
|
113
|
+
say(`step ${i + 1}/${job.steps.length}: ${s.name}${s.cmd ? `: ${redact(s.cmd)}` : ''}`);
|
|
114
|
+
if (s.internal) {
|
|
115
|
+
if (!builtins[s.internal]) throw new Error(`unknown internal step ${s.internal}`);
|
|
116
|
+
await builtins[s.internal](ctx, job, s.args || {});
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const code = await runStep(s.cmd, s.cwd || ctx.env.HOME, env, log, redact);
|
|
120
|
+
if (code !== 0) {
|
|
121
|
+
job.exit = code;
|
|
122
|
+
throw new Error(`"${s.name}" exited with ${code}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
job.status = 'done';
|
|
126
|
+
job.exit = 0;
|
|
127
|
+
say('done');
|
|
128
|
+
} catch (e) {
|
|
129
|
+
job.status = 'failed';
|
|
130
|
+
job.error = redact(String(e.message || e));
|
|
131
|
+
say(`failed: ${job.error}`);
|
|
132
|
+
}
|
|
133
|
+
job.finishedAt = new Date().toISOString();
|
|
134
|
+
write(ctx, job);
|
|
135
|
+
return job;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Status plus the end of the log, for job_status. */
|
|
139
|
+
export function describeJob(ctx, job, lines = 80) {
|
|
140
|
+
return { ...job, log: tail(logOf(ctx, job.id), lines) };
|
|
141
|
+
}
|
package/src/mcp/server.js
CHANGED
|
@@ -16,6 +16,8 @@ import * as resources from '../resources.js';
|
|
|
16
16
|
import * as upgrader from '../upgrade.js';
|
|
17
17
|
import * as cleanup from '../cleanup.js';
|
|
18
18
|
import * as limits from '../limits.js';
|
|
19
|
+
import * as project from '../project.js';
|
|
20
|
+
import * as jobs from '../jobs.js';
|
|
19
21
|
import { Cancelled, NeedsUser, interaction } from './interact.js';
|
|
20
22
|
|
|
21
23
|
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
@@ -107,6 +109,73 @@ export function buildServer(env = process.env, opts = {}) {
|
|
|
107
109
|
return text(`proc ${a.name} removed`);
|
|
108
110
|
});
|
|
109
111
|
|
|
112
|
+
// ---- Managed apps (src/project.js): clone, set up, run, update ---------------------------
|
|
113
|
+
const APP = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/).describe('app name (app_list); a session project name works too');
|
|
114
|
+
const jobReply = (job, what) => text({ job: job.id, status: job.status, note: `${what} runs in the background: follow it with job_status {"id":"${job.id}"}` });
|
|
115
|
+
|
|
116
|
+
tool('app_list', 'Managed apps on this device (cloned with git_clone): folder, repo and branch, detected stack, start command and port, and whether its process runs.', {},
|
|
117
|
+
async (c) => text(project.list(c)));
|
|
118
|
+
|
|
119
|
+
tool('git_clone', 'Clone a repository into the apps folder as a managed app, then detect its stack (job). Private GitHub repos use the device secret GITHUB_TOKEN (or token_secret), passed to git through the environment only. No agent session unless session=true. Next: project_setup, then project_start.',
|
|
120
|
+
{ url: z.string().max(300).describe('https://host/owner/repo(.git), git@host:owner/repo, or file:///path'), name: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/).optional(), branch: z.string().max(100).optional(),
|
|
121
|
+
token_secret: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional().describe('device secret holding a git token (default GITHUB_TOKEN for github.com)'), session: z.boolean().optional().describe('also give it a persistent agent session'), ...FORCE },
|
|
122
|
+
async (c, a) => {
|
|
123
|
+
await guard(c, a, `cloning ${a.url}`);
|
|
124
|
+
return jobReply(await project.clone(c, { url: a.url, name: a.name, branch: a.branch, tokenSecret: a.token_secret, session: a.session }), 'The clone');
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
tool('git_pull', 'Update a managed app from its remote: fetch, then fast-forward only (job). Refuses when the app folder has uncommitted changes, and lists them.',
|
|
128
|
+
{ app: APP, ...FORCE },
|
|
129
|
+
async (c, a) => { await guard(c, a, `pulling ${a.app}`); return jobReply(await project.pull(c, { app: a.app }), 'The pull'); });
|
|
130
|
+
|
|
131
|
+
tool('project_setup', 'Detect how an app is built (node via npm/pnpm/yarn by lockfile, python via uv/poetry/pip, go, ruby, php, docker compose) and install its dependencies and build it (job). Returns the plan: stack, install, build, start command, port.',
|
|
132
|
+
{ app: APP, ...FORCE },
|
|
133
|
+
async (c, a) => {
|
|
134
|
+
await guard(c, a, `setting up ${a.app}`);
|
|
135
|
+
const r = await project.setup(c, { app: a.app });
|
|
136
|
+
return text({ plan: r.plan, ...(r.job ? { job: r.job.id, status: r.job.status, note: `follow it with job_status {"id":"${r.job.id}"}` } : { note: r.note }) });
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
tool('project_start', 'Run an app as a long-running process (restarted on crash and reboot, held to the safe maximums), with its .env loaded and PORT set when known. Uses the detected start command unless command is given.',
|
|
140
|
+
{ app: APP, command: z.string().max(500).optional().describe('one shell line, e.g. "npm run dev -- --port 4000"'), port: z.number().int().min(1).max(65535).optional(), ...FORCE },
|
|
141
|
+
async (c, a) => { await guard(c, a, `starting ${a.app}`); return text(project.start(c, { app: a.app, command: a.command, port: a.port })); });
|
|
142
|
+
|
|
143
|
+
tool('project_stop', 'Stop an app\'s process (asks the user first). The app and its files stay; project_start runs it again.',
|
|
144
|
+
{ app: APP, ...CONFIRM },
|
|
145
|
+
async (c, a, u) => { await u.confirm(`Stop ${a.app}? It stops serving until it is started again.`); return text(project.stop(c, { app: a.app })); });
|
|
146
|
+
|
|
147
|
+
tool('project_deploy', 'Update and redeploy an app in one job: pull (fast-forward), install and build, then restart its process if it runs. What GitHub push webhooks run.',
|
|
148
|
+
{ app: APP, ...FORCE },
|
|
149
|
+
async (c, a) => { await guard(c, a, `deploying ${a.app}`); return jobReply(await project.deploy(c, { app: a.app }), 'The deploy'); });
|
|
150
|
+
|
|
151
|
+
tool('shell_exec', 'Run one shell command in an app\'s folder. Waits up to timeout_seconds (max 120) and returns the exit code and the last 200 lines; longer, or background=true, runs as a job (job_status). Needs device:admin.',
|
|
152
|
+
{ app: APP, command: z.string().min(1).max(4000), timeout_seconds: z.number().int().min(1).max(3600).optional(), background: z.boolean().optional(), ...FORCE },
|
|
153
|
+
async (c, a) => {
|
|
154
|
+
await guard(c, a, 'a shell command');
|
|
155
|
+
const r = await project.shellExec(c, { app: a.app, command: a.command, timeoutSeconds: a.timeout_seconds, background: a.background });
|
|
156
|
+
return r.background ? text({ job: r.job, note: `runs in the background: job_status {"id":"${r.job}"}` }) : { ...(r.exit === 0 ? {} : { isError: true }), content: [{ type: 'text', text: `exit ${r.timedOut ? 'timeout' : r.exit}${r.truncated ? ' (last 200 lines)' : ''}\n${r.output}` }] };
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
tool('file_read', 'Read a text file (numbered lines; offset/limit to page) or list a folder inside an app. Paths are relative to the app folder; .git and .env files are off limits (env_manage lists .env keys).',
|
|
160
|
+
{ app: APP, path: z.string().min(1).max(500), offset: z.number().int().min(1).optional(), limit: z.number().int().min(1).max(2000).optional() },
|
|
161
|
+
async (c, a) => text(project.fileRead(c, { app: a.app, path: a.path, offset: a.offset, limit: a.limit })));
|
|
162
|
+
|
|
163
|
+
tool('file_write', 'Write a text file inside an app (overwrite, append, or create = only if missing). Up to 1 MB; parent folders are created; .git and .env files are off limits (use env_manage).',
|
|
164
|
+
{ app: APP, path: z.string().min(1).max(500), content: z.string(), mode: z.enum(['overwrite', 'append', 'create']).optional() },
|
|
165
|
+
async (c, a) => text(project.fileWrite(c, { app: a.app, path: a.path, content: a.content, mode: a.mode })));
|
|
166
|
+
|
|
167
|
+
tool('env_manage', 'An app\'s .env file: list shows variable names only (values are never returned); set (value, or from_secret to copy a device secret without it passing through you) and unset ask the user first. Applies at the next project_start.',
|
|
168
|
+
{ app: APP, action: z.enum(['list', 'set', 'unset']), key: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,99}$/).optional(), value: z.string().max(4000).optional(),
|
|
169
|
+
from_secret: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional(), file: z.string().regex(/^\.env(\.[a-z0-9_-]{1,20})?$/).optional(), ...CONFIRM },
|
|
170
|
+
async (c, a, u) => {
|
|
171
|
+
if (a.action !== 'list') await u.confirm(`${a.action === 'set' ? 'Set' : 'Remove'} ${a.key} in ${a.app}/${a.file || '.env'}${a.from_secret ? ` (from the device secret ${a.from_secret})` : ''}?`);
|
|
172
|
+
return text(project.envManage(c, { app: a.app, action: a.action, key: a.key, value: a.value, fromSecret: a.from_secret, file: a.file }));
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
tool('job_status', 'A background job (clone, setup, pull, deploy, long shell command): status, current step, exit code and the end of its log. Without id: recent jobs.',
|
|
176
|
+
{ id: z.string().regex(/^[a-z0-9-]{6,40}$/).optional(), lines: z.number().int().min(1).max(500).optional() },
|
|
177
|
+
async (c, a) => text(a.id ? jobs.describeJob(c, jobs.getJob(c, a.id), a.lines || 80) : jobs.listJobs(c).map(({ steps, ...j }) => j)));
|
|
178
|
+
|
|
110
179
|
tool('viewers', 'URLs where the user watches live progress (noVNC display, read-only tmux, Playwright UI) and the SSH tunnel command to reach them.', {},
|
|
111
180
|
async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
|
|
112
181
|
|
package/src/project.js
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
// The project tools: clone, pull, setup, start/stop, deploy, one-off shell
|
|
2
|
+
// commands, files and .env, for managed apps (src/apps.js). Used by the MCP
|
|
3
|
+
// tools (src/mcp/server.js) and the CLI (`harness-device app …`).
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { appsDir, getApp, saveApp, listApps, nameFromUrl, checkRepoUrl, resolveIn, procName, APP_NAME } from './apps.js';
|
|
9
|
+
import { detect } from './stack.js';
|
|
10
|
+
import { startJob } from './jobs.js';
|
|
11
|
+
import * as state from './state.js';
|
|
12
|
+
import { readSecrets } from './context.js';
|
|
13
|
+
import { loadConfig, saveConfig } from './config.js';
|
|
14
|
+
import { checkCap } from './limits.js';
|
|
15
|
+
|
|
16
|
+
const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
17
|
+
const BRANCH = /^[A-Za-z0-9._/-]{1,100}$/;
|
|
18
|
+
const SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
19
|
+
const MAX_READ = 256 * 1024;
|
|
20
|
+
const MAX_WRITE = 1024 * 1024;
|
|
21
|
+
|
|
22
|
+
const running = (ctx, app) => state.listProcs(ctx).some((p) => p.name === procName(app));
|
|
23
|
+
|
|
24
|
+
export function appView(ctx, app) {
|
|
25
|
+
return { ...app, process: procName(app), running: running(ctx, app) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function list(ctx) {
|
|
29
|
+
return listApps(ctx).map((a) => appView(ctx, a));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Steps that install and build an app (from a fresh detect). */
|
|
33
|
+
function setupSteps(app, plan) {
|
|
34
|
+
return [
|
|
35
|
+
...plan.install.map((cmd, i) => ({ name: `install${plan.install.length > 1 ? ` ${i + 1}` : ''}`, cmd, cwd: app.dir })),
|
|
36
|
+
...(plan.build ? [{ name: 'build', cmd: plan.build, cwd: app.dir }] : []),
|
|
37
|
+
];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const CLEAN_CHECK = 'test -z "$(git status --porcelain --untracked-files=no)" || { echo "Uncommitted changes, not pulling:"; git status --short --untracked-files=no; exit 3; }';
|
|
41
|
+
|
|
42
|
+
export async function clone(ctx, { url, name, branch, tokenSecret, session = false }) {
|
|
43
|
+
checkRepoUrl(url);
|
|
44
|
+
const n = name || nameFromUrl(url);
|
|
45
|
+
if (!APP_NAME.test(n)) throw new Error(`App name "${n}" must be lowercase letters, digits, _ or - (max 40)`);
|
|
46
|
+
if (branch && !BRANCH.test(branch)) throw new Error(`Not a branch name: ${branch}`);
|
|
47
|
+
if (tokenSecret && !SECRET_NAME.test(tokenSecret)) throw new Error(`Not a secret name: ${tokenSecret}`);
|
|
48
|
+
if (listApps(ctx).some((a) => a.name === n)) throw new Error(`App "${n}" exists already: use git_pull, or another name`);
|
|
49
|
+
const root = appsDir(ctx);
|
|
50
|
+
const dir = path.join(root, n);
|
|
51
|
+
if (fs.existsSync(dir) && fs.readdirSync(dir).length) throw new Error(`${dir} exists and is not empty`);
|
|
52
|
+
fs.mkdirSync(root, { recursive: true });
|
|
53
|
+
const secret = tokenSecret || (/^https:\/\/github\.com\//.test(url) && readSecrets(ctx.paths.secrets).GITHUB_TOKEN ? 'GITHUB_TOKEN' : null);
|
|
54
|
+
return startJob(ctx, {
|
|
55
|
+
kind: 'clone', app: n, tokenSecret: secret,
|
|
56
|
+
steps: [
|
|
57
|
+
{ name: 'clone', cmd: `git clone --depth 50 ${branch ? `--branch ${q(branch)} ` : ''}${q(url)} ${q(dir)}`, cwd: root },
|
|
58
|
+
{ name: 'register', internal: 'register', args: { name: n, dir, url, branch: branch || null, session: !!session } },
|
|
59
|
+
],
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function pull(ctx, { app: name }) {
|
|
64
|
+
const app = getApp(ctx, name);
|
|
65
|
+
return startJob(ctx, {
|
|
66
|
+
kind: 'pull', app: app.name, tokenSecret: app.tokenSecret || null,
|
|
67
|
+
steps: [
|
|
68
|
+
{ name: 'check for local changes', cmd: CLEAN_CHECK, cwd: app.dir },
|
|
69
|
+
{ name: 'fetch', cmd: 'git fetch --prune origin', cwd: app.dir },
|
|
70
|
+
{ name: 'fast-forward', cmd: 'git merge --ff-only @{u}', cwd: app.dir },
|
|
71
|
+
{ name: 'detect', internal: 'redetect', args: { name: app.name } },
|
|
72
|
+
],
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function setup(ctx, { app: name }) {
|
|
77
|
+
const app = getApp(ctx, name);
|
|
78
|
+
const plan = detect(app.dir);
|
|
79
|
+
if (!app.project) saveApp(ctx, { ...app, stack: plan.stack, start: app.startOverride || plan.start, port: app.port || plan.port });
|
|
80
|
+
const steps = setupSteps(app, plan);
|
|
81
|
+
if (!steps.length) return { plan, job: null, note: plan.notes.join('; ') || 'nothing to install' };
|
|
82
|
+
const job = await startJob(ctx, { kind: 'setup', app: app.name, steps });
|
|
83
|
+
return { plan, job };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The start line: load the app's .env, set PORT when known, then the command. */
|
|
87
|
+
export function startLine(command, port) {
|
|
88
|
+
return `set -a; [ -f .env ] && . ./.env; set +a; ${port ? `export PORT=\${PORT:-${Number(port)}}; ` : ''}exec ${command}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function start(ctx, { app: name, command, port }) {
|
|
92
|
+
const app = getApp(ctx, name);
|
|
93
|
+
const plan = command ? null : detect(app.dir);
|
|
94
|
+
const cmd = command || app.startOverride || app.start || plan?.start;
|
|
95
|
+
if (!cmd) throw new Error(`No start command known for ${app.name}: give one (e.g. "npm start")`);
|
|
96
|
+
if (/\n/.test(cmd)) throw new Error('One line, please');
|
|
97
|
+
const p = port ? Number(port) : app.port || plan?.port || null;
|
|
98
|
+
if (port && !(p >= 1 && p <= 65535)) throw new Error('port must be 1-65535');
|
|
99
|
+
if (!app.project) saveApp(ctx, { ...app, ...(command ? { startOverride: command } : {}), ...(p ? { port: p } : {}) });
|
|
100
|
+
state.addProc(ctx, procName(app), app.dir, startLine(cmd, p));
|
|
101
|
+
return { app: app.name, process: procName(app), command: cmd, port: p, logs: `logs tool, target "proc-${procName(app)}"` };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function stop(ctx, { app: name }) {
|
|
105
|
+
const app = getApp(ctx, name);
|
|
106
|
+
if (!running(ctx, app)) throw new Error(`${app.name} is not running`);
|
|
107
|
+
state.removeProc(ctx, procName(app));
|
|
108
|
+
return { app: app.name, stopped: true };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function deploy(ctx, { app: name }) {
|
|
112
|
+
const app = getApp(ctx, name);
|
|
113
|
+
const plan = detect(app.dir);
|
|
114
|
+
return startJob(ctx, {
|
|
115
|
+
kind: 'deploy', app: app.name, tokenSecret: app.tokenSecret || null,
|
|
116
|
+
steps: [
|
|
117
|
+
{ name: 'check for local changes', cmd: CLEAN_CHECK, cwd: app.dir },
|
|
118
|
+
{ name: 'fetch', cmd: 'git fetch --prune origin', cwd: app.dir },
|
|
119
|
+
{ name: 'fast-forward', cmd: 'git merge --ff-only @{u}', cwd: app.dir },
|
|
120
|
+
...setupSteps(app, plan),
|
|
121
|
+
{ name: 'detect', internal: 'redetect', args: { name: app.name } },
|
|
122
|
+
{ name: 'restart if running', internal: 'restart', args: { name: app.name } },
|
|
123
|
+
],
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Run one command in the app folder: wait up to timeout (≤120s), else as a job. */
|
|
128
|
+
export async function shellExec(ctx, { app: name, command, timeoutSeconds = 60, background = false }) {
|
|
129
|
+
const app = getApp(ctx, name);
|
|
130
|
+
if (!command || /\0/.test(command)) throw new Error('Give a command');
|
|
131
|
+
const t = Math.max(1, Math.min(Number(timeoutSeconds) || 60, 3600));
|
|
132
|
+
if (background || t > 120) {
|
|
133
|
+
const job = await startJob(ctx, { kind: 'exec', app: app.name, steps: [{ name: 'command', cmd: command, cwd: app.dir }] });
|
|
134
|
+
return { background: true, job: job.id };
|
|
135
|
+
}
|
|
136
|
+
const env = { ...ctx.env, CI: '1' };
|
|
137
|
+
for (const k of ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX']) delete env[k];
|
|
138
|
+
return new Promise((resolve) => {
|
|
139
|
+
const child = spawn('bash', ['-lc', command], { cwd: app.dir, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
|
|
140
|
+
let out = '';
|
|
141
|
+
const add = (b) => { out += b; if (out.length > 400_000) out = out.slice(-200_000); };
|
|
142
|
+
child.stdout.on('data', add);
|
|
143
|
+
child.stderr.on('data', add);
|
|
144
|
+
let timedOut = false;
|
|
145
|
+
const timer = setTimeout(() => { timedOut = true; try { process.kill(-child.pid, 'SIGTERM'); } catch { /* gone */ } }, t * 1000);
|
|
146
|
+
child.on('close', (code) => {
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
const lines = out.split('\n');
|
|
149
|
+
resolve({ exit: timedOut ? null : code, timedOut, output: lines.slice(-200).join('\n'), truncated: lines.length > 200 });
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function fileRead(ctx, { app: name, path: rel, offset = 1, limit = 400 }) {
|
|
155
|
+
const app = getApp(ctx, name);
|
|
156
|
+
const f = resolveIn(app, rel);
|
|
157
|
+
if (!fs.existsSync(f)) throw new Error(`No file ${rel}`);
|
|
158
|
+
const st = fs.statSync(f);
|
|
159
|
+
if (st.isDirectory()) {
|
|
160
|
+
return { path: rel, directory: true, entries: fs.readdirSync(f, { withFileTypes: true }).filter((e) => e.name !== '.git').map((e) => (e.isDirectory() ? `${e.name}/` : e.name)).sort() };
|
|
161
|
+
}
|
|
162
|
+
if (st.size > MAX_READ * 8) throw new Error(`${rel} is ${Math.round(st.size / 1024)} KB: too big to read here`);
|
|
163
|
+
const buf = fs.readFileSync(f);
|
|
164
|
+
if (buf.subarray(0, 8000).includes(0)) throw new Error(`${rel} looks binary`);
|
|
165
|
+
const lines = buf.toString('utf8').split('\n');
|
|
166
|
+
const from = Math.max(1, Number(offset) || 1);
|
|
167
|
+
const n = Math.max(1, Math.min(Number(limit) || 400, 2000));
|
|
168
|
+
let text = lines.slice(from - 1, from - 1 + n).map((l, i) => `${String(from + i).padStart(5)} ${l}`).join('\n');
|
|
169
|
+
if (text.length > MAX_READ) text = text.slice(0, MAX_READ);
|
|
170
|
+
return { path: rel, lines: lines.length, from, to: Math.min(lines.length, from - 1 + n), text };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function fileWrite(ctx, { app: name, path: rel, content, mode = 'overwrite' }) {
|
|
174
|
+
const app = getApp(ctx, name);
|
|
175
|
+
if (typeof content !== 'string') throw new Error('content must be text');
|
|
176
|
+
if (Buffer.byteLength(content) > MAX_WRITE) throw new Error('content is over 1 MB');
|
|
177
|
+
const f = resolveIn(app, rel);
|
|
178
|
+
if (fs.existsSync(f) && fs.statSync(f).isDirectory()) throw new Error(`${rel} is a folder`);
|
|
179
|
+
if (mode === 'create' && fs.existsSync(f)) throw new Error(`${rel} exists (mode "create" never overwrites)`);
|
|
180
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
181
|
+
if (mode === 'append') fs.appendFileSync(f, content);
|
|
182
|
+
else fs.writeFileSync(f, content);
|
|
183
|
+
return { path: rel, bytes: fs.statSync(f).size, mode };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---- .env -----------------------------------------------------------------------------
|
|
187
|
+
const ENV_FILE = /^\.env(\.[a-z0-9_-]{1,20})?$/;
|
|
188
|
+
const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]{0,99}$/;
|
|
189
|
+
|
|
190
|
+
function envPath(app, file) {
|
|
191
|
+
if (!ENV_FILE.test(file)) throw new Error(`Not an env file name: ${file} (.env or .env.<name>)`);
|
|
192
|
+
return resolveIn(app, file, { allowEnv: true });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const keysOf = (text) => text.split('\n').map((l) => l.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/)).filter(Boolean).map((m) => m[1]);
|
|
196
|
+
|
|
197
|
+
/** list → names only; set/unset → rewrite that line, keep the rest. Values are never returned. */
|
|
198
|
+
export function envManage(ctx, { app: name, action, key, value, fromSecret, file = '.env' }) {
|
|
199
|
+
const app = getApp(ctx, name);
|
|
200
|
+
const f = envPath(app, file);
|
|
201
|
+
const text = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '';
|
|
202
|
+
if (action === 'list') return { file, keys: keysOf(text) };
|
|
203
|
+
if (!ENV_KEY.test(String(key || ''))) throw new Error(`Not an env variable name: ${key}`);
|
|
204
|
+
const lines = text.split('\n').filter((l, i, a) => !(i === a.length - 1 && l === ''));
|
|
205
|
+
const keep = lines.filter((l) => !new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`).test(l));
|
|
206
|
+
if (action === 'unset') {
|
|
207
|
+
if (keep.length === lines.length) throw new Error(`${key} is not in ${file}`);
|
|
208
|
+
} else if (action === 'set') {
|
|
209
|
+
let v = value;
|
|
210
|
+
if (fromSecret) {
|
|
211
|
+
if (!SECRET_NAME.test(fromSecret)) throw new Error(`Not a secret name: ${fromSecret}`);
|
|
212
|
+
v = readSecrets(ctx.paths.secrets)[fromSecret];
|
|
213
|
+
if (v === undefined) throw new Error(`No device secret ${fromSecret} (set it on the machine, or as a pool secret)`);
|
|
214
|
+
}
|
|
215
|
+
if (typeof v !== 'string' || /[\n\r\0]/.test(v)) throw new Error('Give value (one line) or from_secret');
|
|
216
|
+
keep.push(`${key}="${v.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\$/g, '\\$').replace(/`/g, '\\`')}"`);
|
|
217
|
+
} else {
|
|
218
|
+
throw new Error('action is list, set or unset');
|
|
219
|
+
}
|
|
220
|
+
fs.writeFileSync(f, keep.join('\n') + '\n', { mode: 0o600 });
|
|
221
|
+
fs.chmodSync(f, 0o600);
|
|
222
|
+
return { file, keys: keysOf(keep.join('\n')), changed: key, note: running(ctx, app) ? `restart to apply: project_stop then project_start ${app.name}` : 'applies at the next project_start' };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// ---- Steps the job runner performs in-process ----------------------------------------
|
|
226
|
+
export const INTERNALS = {
|
|
227
|
+
async register(ctx, job, { name, dir, url, branch, session }) {
|
|
228
|
+
const plan = detect(dir);
|
|
229
|
+
saveApp(ctx, { name, dir, repo: url, branch, tokenSecret: job.tokenSecret || null, stack: plan.stack, start: plan.start, port: plan.port, createdAt: new Date().toISOString() });
|
|
230
|
+
if (session) {
|
|
231
|
+
checkCap(ctx, 'session', state.listSessions(ctx).length);
|
|
232
|
+
const { cfg } = loadConfig(ctx.env);
|
|
233
|
+
saveConfig({ ...cfg, [`PROJECT_${name}`]: dir }, ctx.env);
|
|
234
|
+
state.applyLayout(ctx);
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
async redetect(ctx, _job, { name }) {
|
|
238
|
+
const app = getApp(ctx, name);
|
|
239
|
+
if (app.project) return;
|
|
240
|
+
const plan = detect(app.dir);
|
|
241
|
+
saveApp(ctx, { ...app, stack: plan.stack, start: app.startOverride || plan.start, port: app.port || plan.port });
|
|
242
|
+
},
|
|
243
|
+
async restart(ctx, _job, { name }) {
|
|
244
|
+
const app = getApp(ctx, name);
|
|
245
|
+
const p = state.listProcs(ctx).find((x) => x.name === procName(app));
|
|
246
|
+
if (p) state.addProc(ctx, p.name, p.dir, p.command); // re-adding restarts its window
|
|
247
|
+
},
|
|
248
|
+
};
|
package/src/providers/claude.js
CHANGED
|
@@ -167,7 +167,8 @@ export function userMcpServers(env) {
|
|
|
167
167
|
// harness-device MCP tools that only read, or restart the browser. proc_add,
|
|
168
168
|
// proc_remove, restart_service and playwright_ui still ask: they start or stop things.
|
|
169
169
|
export const HARNESS_TOOLS_ALLOWED = ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs',
|
|
170
|
-
'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status', 'config_get', 'resources'
|
|
170
|
+
'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status', 'config_get', 'resources',
|
|
171
|
+
'app_list', 'file_read', 'job_status'].map((t) => `mcp__harness-device__${t}`);
|
|
171
172
|
|
|
172
173
|
/**
|
|
173
174
|
* A Read() rule for an absolute path. In Claude Code rules `/x` is relative to
|
package/src/serve/scopes.js
CHANGED
|
@@ -11,8 +11,11 @@ export const SCOPES = {
|
|
|
11
11
|
const ORDER = ['device:read', 'device:operate', 'device:admin'];
|
|
12
12
|
|
|
13
13
|
const TOOLS = {
|
|
14
|
-
'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get'
|
|
15
|
-
|
|
14
|
+
'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get',
|
|
15
|
+
'app_list', 'file_read', 'job_status'],
|
|
16
|
+
'device:operate': ['proc_add', 'proc_remove', 'session_new', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit',
|
|
17
|
+
'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage'],
|
|
18
|
+
// shell_exec is not listed: it needs device:admin (unknown tools do).
|
|
16
19
|
};
|
|
17
20
|
|
|
18
21
|
/** Granted scopes with everything they include. */
|
package/src/stack.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// What kind of project a folder is, and how to install, build and start it.
|
|
2
|
+
// Pure: reads files only. The commands run later in a job (src/jobs.js), in
|
|
3
|
+
// the project folder, through `bash -lc`.
|
|
4
|
+
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
|
|
8
|
+
const has = (dir, f) => fs.existsSync(path.join(dir, f));
|
|
9
|
+
const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
|
|
10
|
+
|
|
11
|
+
/** A port a start script names (--port 3000, -p 5173, PORT=8080), if any. */
|
|
12
|
+
export function portFrom(script = '') {
|
|
13
|
+
const m = String(script).match(/(?:--port[ =]|-p |PORT=)(\d{2,5})\b/);
|
|
14
|
+
return m ? Number(m[1]) : null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* { stack, install: [cmd], build: cmd|null, start: cmd|null, port: n|null, notes: [..] }
|
|
19
|
+
* install/build/start are shell lines for the project folder.
|
|
20
|
+
*/
|
|
21
|
+
export function detect(dir) {
|
|
22
|
+
const notes = [];
|
|
23
|
+
if (has(dir, 'package.json')) {
|
|
24
|
+
const pkg = readJson(path.join(dir, 'package.json')) || {};
|
|
25
|
+
const scripts = pkg.scripts || {};
|
|
26
|
+
let pm = 'npm';
|
|
27
|
+
let install = 'npm install --no-audit --no-fund';
|
|
28
|
+
if (has(dir, 'pnpm-lock.yaml')) { pm = 'pnpm'; install = 'npx -y pnpm@9 install --frozen-lockfile'; }
|
|
29
|
+
else if (has(dir, 'yarn.lock')) { pm = 'yarn'; install = 'npx -y yarn@1 install --frozen-lockfile'; }
|
|
30
|
+
else if (has(dir, 'package-lock.json')) install = 'npm ci --no-audit --no-fund';
|
|
31
|
+
const run = (s) => (pm === 'npm' ? `npm run ${s}` : pm === 'pnpm' ? `npx -y pnpm@9 run ${s}` : `npx -y yarn@1 run ${s}`);
|
|
32
|
+
const startScript = scripts.start ? 'start' : scripts.dev ? 'dev' : null;
|
|
33
|
+
if (!startScript && pkg.main) notes.push(`no start or dev script; "node ${pkg.main}" may start it`);
|
|
34
|
+
return {
|
|
35
|
+
stack: 'node',
|
|
36
|
+
install: [install],
|
|
37
|
+
build: scripts.build ? run('build') : null,
|
|
38
|
+
start: startScript ? (startScript === 'start' && pm === 'npm' ? 'npm start' : run(startScript)) : (pkg.main ? `node ${pkg.main}` : null),
|
|
39
|
+
port: portFrom(scripts[startScript] || '') ,
|
|
40
|
+
notes,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
if (has(dir, 'docker-compose.yml') || has(dir, 'compose.yaml') || has(dir, 'docker-compose.yaml') || has(dir, 'compose.yml')) {
|
|
44
|
+
return { stack: 'compose', install: [], build: 'docker compose build', start: 'docker compose up', port: null, notes: ['runs in the foreground so the process loop keeps it up; stop it with project_stop'] };
|
|
45
|
+
}
|
|
46
|
+
if (has(dir, 'pyproject.toml') || has(dir, 'requirements.txt')) {
|
|
47
|
+
let install;
|
|
48
|
+
if (has(dir, 'uv.lock')) install = 'uv sync';
|
|
49
|
+
else if (has(dir, 'poetry.lock')) install = 'poetry install';
|
|
50
|
+
else if (has(dir, 'requirements.txt')) install = 'python3 -m venv .venv && .venv/bin/pip install -q -r requirements.txt';
|
|
51
|
+
else install = 'python3 -m venv .venv && .venv/bin/pip install -q -e .';
|
|
52
|
+
let start = null;
|
|
53
|
+
if (has(dir, 'manage.py')) start = '.venv/bin/python manage.py runserver 0.0.0.0:8000';
|
|
54
|
+
else if (has(dir, 'main.py')) start = '.venv/bin/python main.py';
|
|
55
|
+
else if (has(dir, 'app.py')) start = '.venv/bin/python app.py';
|
|
56
|
+
if (start && !install.includes('.venv')) start = start.replace('.venv/bin/python', install.startsWith('uv') ? 'uv run python' : 'poetry run python');
|
|
57
|
+
return { stack: 'python', install: [install], build: null, start, port: has(dir, 'manage.py') ? 8000 : null, notes };
|
|
58
|
+
}
|
|
59
|
+
if (has(dir, 'go.mod')) return { stack: 'go', install: ['go mod download'], build: 'go build -o .bin/app .', start: './.bin/app', port: null, notes };
|
|
60
|
+
if (has(dir, 'Gemfile')) {
|
|
61
|
+
const rails = has(dir, 'config.ru') && has(dir, 'bin/rails');
|
|
62
|
+
return { stack: 'ruby', install: ['bundle install'], build: null, start: rails ? 'bin/rails server -b 0.0.0.0' : null, port: rails ? 3000 : null, notes };
|
|
63
|
+
}
|
|
64
|
+
if (has(dir, 'composer.json')) return { stack: 'php', install: ['composer install --no-interaction'], build: null, start: has(dir, 'artisan') ? 'php artisan serve --host 0.0.0.0' : null, port: has(dir, 'artisan') ? 8000 : null, notes };
|
|
65
|
+
if (has(dir, 'Dockerfile')) notes.push('only a Dockerfile: build and run it with shell_exec, or add a compose file');
|
|
66
|
+
return { stack: 'unknown', install: [], build: null, start: null, port: null, notes: [...notes, 'no package.json, pyproject/requirements, go.mod, Gemfile, composer.json or compose file found: give project_start a command'] };
|
|
67
|
+
}
|