@dreamtree-org/harness-device 0.2.1 → 0.4.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 +23 -0
- package/package.json +1 -1
- package/src/apps.js +90 -0
- package/src/capabilities.js +10 -1
- package/src/cli.js +28 -2
- package/src/config.js +7 -0
- package/src/exec.js +77 -0
- package/src/jobs.js +282 -0
- package/src/limits.js +11 -2
- package/src/mcp/server.js +93 -0
- package/src/project.js +248 -0
- package/src/providers/claude.js +2 -1
- package/src/serve/scopes.js +6 -2
- package/src/stack.js +67 -0
package/README.md
CHANGED
|
@@ -193,6 +193,29 @@ 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
|
+
| `exec` | One program with an argv and no shell. The program must be on `EXEC_ALLOW` (a default list of dev tools); shells and wrappers such as `bash`, `env`, `sudo` or `xargs` are always refused. Runs in the app folder or a confined sub-folder. `env_refs` injects device secrets by name and redacts them from output. Timeout and output cap (head and tail kept). A durable job: `job_status` with `offset` streams new output, `job_cancel` kills the whole process tree. Never restarted. Linux holds the per-process caps in a systemd scope; on macOS the watchdog covers running jobs. Each run is recorded in `events` (program, folder, outcome, exit code, duration; never env or output) |
|
|
210
|
+
| `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` |
|
|
211
|
+
| `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
|
|
212
|
+
|
|
213
|
+
**Recovering a job** (`exec`, clone, setup, deploy):
|
|
214
|
+
- `job_status {id}` shows its status, step, pid and the end of its log; `job_status {id, offset}` continues the log from a byte offset.
|
|
215
|
+
- `job_cancel {id}` ends a stuck one, killing its whole process group (TERM, then KILL after 5s).
|
|
216
|
+
- Records and logs are in `~/.harness-device/state/jobs/` and `logs/jobs/`, and the last 50 are kept. A job the watchdog stops for going over its caps ends as failed, with an event.
|
|
217
|
+
- A job whose runner died, for example in a reboot, still shows as running with a dead pid. `job_cancel` clears it.
|
|
218
|
+
|
|
196
219
|
### Join a pool (HarnessPro)
|
|
197
220
|
|
|
198
221
|
`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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreamtree-org/harness-device",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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,16 @@ 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
|
+
- One-off programs: \`exec\` with an argv (no shell), e.g. \`{"app":"web","argv":["npm","test"]}\`. The program must be on the allowlist; secrets go in by name with \`env_refs\` and are redacted from output. Long runs come back as a job id: stream with \`job_status\` (offset), stop with \`job_cancel\`. Prefer it to \`proc_add\` for anything that should end, and to \`shell_exec\` whenever shell syntax isn't needed.
|
|
115
|
+
- \`shell_exec\` runs one shell command in an app folder; through the pool it needs device:admin.
|
|
116
|
+
- 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.
|
|
117
|
+
|
|
118
|
+
## Device, disk and services
|
|
110
119
|
- Overview: \`harness-device status\` (or the \`device_status\` / \`disk_usage\` MCP tools).
|
|
111
120
|
- Disk: \`df -h\`, \`du -sh <dir>\`. ${isMac(plat)
|
|
112
121
|
? '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
|
@@ -57,6 +57,9 @@ ${color.bold('Device')}
|
|
|
57
57
|
join <hub-url> --enroll <secret> join a HarnessPro pool (the dashboard's install command runs this)
|
|
58
58
|
leave leave the pool and forget its credential
|
|
59
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
|
|
60
63
|
limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
|
|
61
64
|
cleanup [--apply] [item...] [--json] what could be freed safely (caches, build cache, old reports/logs); --apply removes it
|
|
62
65
|
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
@@ -77,8 +80,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
77
80
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
78
81
|
`;
|
|
79
82
|
|
|
80
|
-
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart', 'enforce', 'quiet', 'systemSteps'];
|
|
81
|
-
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'];
|
|
82
85
|
|
|
83
86
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
84
87
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -320,6 +323,29 @@ export async function main(argv) {
|
|
|
320
323
|
return install(loadContext(env), { skipSystem: true, graceful: true });
|
|
321
324
|
}
|
|
322
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
|
+
|
|
323
349
|
case 'cleanup': {
|
|
324
350
|
const ctx = loadContext(env);
|
|
325
351
|
const items = cleanup.plan(ctx);
|
package/src/config.js
CHANGED
|
@@ -98,6 +98,11 @@ 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: '',
|
|
103
|
+
// Programs the exec tool may run (comma list; empty = the default list in
|
|
104
|
+
// src/exec.js). Shells and wrappers are refused whatever this says.
|
|
105
|
+
EXEC_ALLOW: '',
|
|
101
106
|
};
|
|
102
107
|
}
|
|
103
108
|
|
|
@@ -210,6 +215,8 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
210
215
|
if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
|
|
211
216
|
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
212
217
|
errs.push(...limitsMod.validate(cfg));
|
|
218
|
+
if (cfg.EXEC_ALLOW && !/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}(,[A-Za-z0-9][A-Za-z0-9._+-]{0,63})*$/.test(String(cfg.EXEC_ALLOW).replace(/\s/g, ''))) errs.push('EXEC_ALLOW must be a comma-separated list of program names.');
|
|
219
|
+
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
220
|
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
221
|
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
222
|
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/exec.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Controlled one-shot execution (HARNESS-4): structured argv, no shell.
|
|
2
|
+
//
|
|
3
|
+
// - The executable is a bare name resolved on PATH and must be on the
|
|
4
|
+
// allowlist (EXEC_ALLOW). Shells and privilege/indirection wrappers are
|
|
5
|
+
// never allowed here, whatever the allowlist says: shell mode is the
|
|
6
|
+
// separate shell_exec tool (device:admin).
|
|
7
|
+
// - It runs in the app's folder (or a sub-folder, confined like file_read).
|
|
8
|
+
// - env_refs inject named device secrets for this run only; their values are
|
|
9
|
+
// redacted from the output. Nothing else secret is inherited (cleanEnv).
|
|
10
|
+
// - Every run is a durable job (src/jobs.js): own process group, timeout,
|
|
11
|
+
// output cap (head + tail kept), cancel kills the whole tree, exit code and
|
|
12
|
+
// byte counts recorded, never restarted. Linux: a systemd scope holds the
|
|
13
|
+
// per-process memory/CPU caps; macOS: the watchdog covers running jobs.
|
|
14
|
+
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { getApp, resolveIn } from './apps.js';
|
|
18
|
+
import { startJob, getJob } from './jobs.js';
|
|
19
|
+
import { readSecrets } from './context.js';
|
|
20
|
+
import { which } from './util.js';
|
|
21
|
+
|
|
22
|
+
export const DEFAULT_ALLOW = ['node', 'npm', 'npx', 'pnpm', 'yarn', 'python3', 'python', 'pip', 'pip3', 'uv', 'poetry', 'go', 'git', 'make', 'docker', 'bundle', 'ruby', 'composer', 'php', 'cargo', 'java', 'mvn', 'gradle', 'pytest', 'jest', 'vitest', 'tsc', 'eslint', 'prettier'];
|
|
23
|
+
/** Never through exec: shells, privilege changes, and wrappers that would run something else unchecked. */
|
|
24
|
+
export const NEVER = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'csh', 'tcsh', 'fish', 'env', 'sudo', 'su', 'doas', 'pkexec', 'xargs', 'nohup', 'setsid', 'nice', 'timeout', 'stdbuf', 'script', 'expect', 'ssh', 'scp', 'eval', 'exec', 'busybox']);
|
|
25
|
+
const BARE = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/;
|
|
26
|
+
const ENV_VAR = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
|
|
27
|
+
const ENV_DENY = /^(PATH|HOME|USER|SHELL|IFS|ENV|BASH_ENV|LD_.*|DYLD_.*|NODE_OPTIONS|NODE_PATH|PYTHONPATH|PYTHONSTARTUP|GIT_.*|SSH_.*|HARNESS_DEVICE_HOME|HD_.*|ANTHROPIC_.*|CLAUDE_.*)$/;
|
|
28
|
+
const SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
29
|
+
export const MAX_TIMEOUT = 3600;
|
|
30
|
+
export const MAX_OUTPUT_KB = 4096;
|
|
31
|
+
|
|
32
|
+
export function allowList(cfg) {
|
|
33
|
+
const s = String(cfg.EXEC_ALLOW || '').trim();
|
|
34
|
+
return s ? s.split(',').map((x) => x.trim()).filter(Boolean) : DEFAULT_ALLOW;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The checked command: { exe (absolute), argv, cwd, envRefs }. Throws with a reason. */
|
|
38
|
+
export function checkExec(ctx, { app: name, argv, cwd = '.', envRefs = {} }) {
|
|
39
|
+
if (!Array.isArray(argv) || !argv.length || argv.some((a) => typeof a !== 'string' || a.includes('\0'))) throw new Error('argv must be a non-empty list of strings');
|
|
40
|
+
if (argv.length > 200 || argv.join('').length > 32 * 1024) throw new Error('argv is too long');
|
|
41
|
+
const exe = argv[0];
|
|
42
|
+
if (!BARE.test(exe)) throw new Error(`"${exe}": give the program's name (e.g. npm), not a path`);
|
|
43
|
+
if (NEVER.has(exe)) throw new Error(`"${exe}" is not allowed in exec (shells and wrappers never are); shell mode is shell_exec, which needs device:admin`);
|
|
44
|
+
if (!allowList(ctx.cfg).includes(exe)) throw new Error(`"${exe}" is not on this device's exec allowlist (EXEC_ALLOW): ${allowList(ctx.cfg).join(', ')}`);
|
|
45
|
+
const resolved = which(exe, ctx.env);
|
|
46
|
+
if (!resolved) throw new Error(`"${exe}" is not installed on this device (not on PATH)`);
|
|
47
|
+
const app = getApp(ctx, name);
|
|
48
|
+
const dir = cwd === '.' || cwd === '' ? fs.realpathSync(app.dir) : resolveIn(app, cwd);
|
|
49
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`cwd ${cwd} is not a folder in ${app.name}`);
|
|
50
|
+
const secrets = readSecrets(ctx.paths.secrets);
|
|
51
|
+
for (const [v, s] of Object.entries(envRefs || {})) {
|
|
52
|
+
if (!ENV_VAR.test(v) || ENV_DENY.test(v)) throw new Error(`env_refs: ${v} can't be set this way`);
|
|
53
|
+
if (!SECRET_NAME.test(String(s)) || secrets[s] === undefined) throw new Error(`env_refs: no device secret ${s}`);
|
|
54
|
+
}
|
|
55
|
+
return { app, exe: resolved, argv: [resolved, ...argv.slice(1)], cwd: dir, envRefs: envRefs || {} };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Start it as a job; wait up to waitSeconds for it to finish. Returns the job
|
|
60
|
+
* (finished, or still running with its id for job_status / job_cancel).
|
|
61
|
+
*/
|
|
62
|
+
export async function exec(ctx, { app, argv, cwd, envRefs, timeoutSeconds = 600, maxOutputKb = 256, waitSeconds = 30 }) {
|
|
63
|
+
const c = checkExec(ctx, { app, argv, cwd, envRefs });
|
|
64
|
+
const t = Math.max(1, Math.min(Number(timeoutSeconds) || 600, MAX_TIMEOUT));
|
|
65
|
+
const kb = Math.max(1, Math.min(Number(maxOutputKb) || 256, MAX_OUTPUT_KB));
|
|
66
|
+
const started = await startJob(ctx, {
|
|
67
|
+
kind: 'exec', app: c.app.name, timeoutSeconds: t, maxOutputBytes: kb * 1024, envRefs: c.envRefs,
|
|
68
|
+
steps: [{ name: path.basename(c.exe), argv: c.argv, cwd: c.cwd }],
|
|
69
|
+
});
|
|
70
|
+
const deadline = Date.now() + Math.max(0, Math.min(Number(waitSeconds) || 0, 120)) * 1000;
|
|
71
|
+
let job = started;
|
|
72
|
+
while (['queued', 'running'].includes(job.status) && Date.now() < deadline) {
|
|
73
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
74
|
+
job = getJob(ctx, started.id);
|
|
75
|
+
}
|
|
76
|
+
return job;
|
|
77
|
+
}
|
package/src/jobs.js
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
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, spawnSync } from 'node:child_process';
|
|
15
|
+
import { readSecrets } from './context.js';
|
|
16
|
+
import { PKG_ROOT, which } from './util.js';
|
|
17
|
+
import { limits as computeLimits } from './limits.js';
|
|
18
|
+
|
|
19
|
+
const KEEP = 50;
|
|
20
|
+
const dirOf = (ctx) => path.join(ctx.paths.state, 'jobs');
|
|
21
|
+
const fileOf = (ctx, id) => path.join(dirOf(ctx), `${id}.json`);
|
|
22
|
+
export const logOf = (ctx, id) => path.join(ctx.paths.logs, 'jobs', `${id}.log`);
|
|
23
|
+
|
|
24
|
+
function write(ctx, job) {
|
|
25
|
+
fs.mkdirSync(dirOf(ctx), { recursive: true });
|
|
26
|
+
const tmp = `${fileOf(ctx, job.id)}.${process.pid}.tmp`;
|
|
27
|
+
fs.writeFileSync(tmp, JSON.stringify(job, null, 2));
|
|
28
|
+
fs.renameSync(tmp, fileOf(ctx, job.id));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function getJob(ctx, id) {
|
|
32
|
+
if (!/^[a-z0-9-]{6,40}$/.test(String(id || ''))) throw new Error(`Not a job id: ${id}`);
|
|
33
|
+
const f = fileOf(ctx, id);
|
|
34
|
+
if (!fs.existsSync(f)) throw new Error(`No job ${id}`);
|
|
35
|
+
return JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function listJobs(ctx, n = 20) {
|
|
39
|
+
const d = dirOf(ctx);
|
|
40
|
+
if (!fs.existsSync(d)) return [];
|
|
41
|
+
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; } })
|
|
42
|
+
.filter(Boolean).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, n);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function prune(ctx) {
|
|
46
|
+
const all = listJobs(ctx, 10000);
|
|
47
|
+
for (const j of all.slice(KEEP)) {
|
|
48
|
+
fs.rmSync(fileOf(ctx, j.id), { force: true });
|
|
49
|
+
fs.rmSync(logOf(ctx, j.id), { force: true });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function tail(file, lines = 80) {
|
|
54
|
+
try {
|
|
55
|
+
const t = fs.readFileSync(file, 'utf8').split('\n');
|
|
56
|
+
return t.slice(-lines - 1).join('\n').trim();
|
|
57
|
+
} catch { return ''; }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Create a job and start it detached. steps: [{ name, cmd, cwd } | { name, internal, args }].
|
|
62
|
+
* tokenSecret: the name of a device secret git may use for https://github.com.
|
|
63
|
+
* Returns the job.
|
|
64
|
+
*/
|
|
65
|
+
export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null }) {
|
|
66
|
+
const id = `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
|
|
67
|
+
const job = {
|
|
68
|
+
id, kind, app, status: 'queued', step: null,
|
|
69
|
+
steps: steps.map((s) => ({ name: s.name, cmd: s.cmd || null, argv: s.argv || null, cwd: s.cwd || null, internal: s.internal || null, args: s.args || null })),
|
|
70
|
+
tokenSecret, envRefs, timeoutSeconds, maxOutputBytes, exit: null, error: null, pid: null, timedOut: false, cancelRequested: false, cancelled: false,
|
|
71
|
+
outputBytes: 0, createdAt: new Date().toISOString(), startedAt: null, finishedAt: null,
|
|
72
|
+
};
|
|
73
|
+
write(ctx, job);
|
|
74
|
+
prune(ctx);
|
|
75
|
+
fs.mkdirSync(path.dirname(logOf(ctx, id)), { recursive: true });
|
|
76
|
+
if (inline || ctx.env.HD_JOBS_INLINE === '1') return runJob(ctx, id).then(() => getJob(ctx, id));
|
|
77
|
+
const bin = path.join(PKG_ROOT, 'bin', 'harness-device.js');
|
|
78
|
+
const args = [process.execPath, bin, 'job', 'run', id];
|
|
79
|
+
if (ctx.platform.id === 'linux' && !scopesWork(ctx.env)) {
|
|
80
|
+
// No user systemd session (container, CI, `su` shell): a plain detached
|
|
81
|
+
// runner instead of a systemd unit, so the job still runs.
|
|
82
|
+
const fd = fs.openSync(logOf(ctx, id), 'a');
|
|
83
|
+
const child = spawn(args[0], args.slice(1), { env: ctx.env, detached: true, stdio: ['ignore', fd, fd] });
|
|
84
|
+
child.unref();
|
|
85
|
+
fs.closeSync(fd);
|
|
86
|
+
} else {
|
|
87
|
+
ctx.platform.spawnDetached(ctx, `job-${id}`, args, logOf(ctx, id));
|
|
88
|
+
}
|
|
89
|
+
return Promise.resolve(job);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The environment a job gets: never Anthropic keys, pool or serve credentials. */
|
|
93
|
+
export function cleanEnv(env) {
|
|
94
|
+
const e = { ...env };
|
|
95
|
+
for (const k of Object.keys(e)) if (/^(ANTHROPIC_|CLAUDE_CODE_USE_|POOL_|SERVE_OWNER_PASSWORD$|RUNLOOM_)/.test(k)) delete e[k];
|
|
96
|
+
return e;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Git auth through the environment only (GIT_CONFIG_*), for https://github.com. */
|
|
100
|
+
export function gitAuthEnv(token) {
|
|
101
|
+
if (!token) return {};
|
|
102
|
+
const basic = Buffer.from(`x-access-token:${token}`).toString('base64');
|
|
103
|
+
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' };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Output kept for a step: up to max bytes in the log, as the first half and the
|
|
108
|
+
* last half with a marker between (stdout and stderr interleaved as they come).
|
|
109
|
+
*/
|
|
110
|
+
function cappedWriter(fd, max, redact) {
|
|
111
|
+
let written = 0;
|
|
112
|
+
let total = 0;
|
|
113
|
+
let tail = '';
|
|
114
|
+
const head = Math.floor(max / 2);
|
|
115
|
+
return {
|
|
116
|
+
write(chunk) {
|
|
117
|
+
const s = redact(String(chunk));
|
|
118
|
+
total += Buffer.byteLength(s);
|
|
119
|
+
if (written < head) {
|
|
120
|
+
const room = head - written;
|
|
121
|
+
const part = Buffer.from(s).subarray(0, room).toString();
|
|
122
|
+
fs.writeSync(fd, part);
|
|
123
|
+
written += Buffer.byteLength(part);
|
|
124
|
+
const rest = s.slice(part.length);
|
|
125
|
+
if (rest) tail = (tail + rest).slice(-(max - head));
|
|
126
|
+
} else {
|
|
127
|
+
tail = (tail + s).slice(-(max - head));
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
end() {
|
|
131
|
+
if (total > written + Buffer.byteLength(tail)) fs.writeSync(fd, `\n[… ${total - written - Buffer.byteLength(tail)} bytes of output omitted …]\n`);
|
|
132
|
+
if (tail) fs.writeSync(fd, tail);
|
|
133
|
+
return total;
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Does `systemd-run --user --scope` work here? Not without a user systemd
|
|
140
|
+
* session (containers, CI runners, a plain `su` shell): then the watchdog
|
|
141
|
+
* holds the caps instead. Probed once per process, like hd-proc-loop does.
|
|
142
|
+
*/
|
|
143
|
+
const scopeProbe = new Map();
|
|
144
|
+
export function scopesWork(env) {
|
|
145
|
+
const bin = which('systemd-run', env);
|
|
146
|
+
if (!bin) return false;
|
|
147
|
+
if (!scopeProbe.has(bin)) {
|
|
148
|
+
const r = spawnSync(bin, ['--user', '--scope', '--quiet', '-p', 'MemoryMax=64M', 'true'], { env, stdio: 'ignore', timeout: 10000 });
|
|
149
|
+
scopeProbe.set(bin, r.status === 0);
|
|
150
|
+
}
|
|
151
|
+
return scopeProbe.get(bin);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Linux: run inside a transient systemd scope holding the per-process caps (plain when scopes don't work here). */
|
|
155
|
+
function scoped(ctx, argv, name) {
|
|
156
|
+
if (ctx.platform.id !== 'linux' || ctx.env.HD_JOBS_NO_SCOPE === '1' || !scopesWork(ctx.env)) return argv;
|
|
157
|
+
const l = computeLimits(ctx.cfg);
|
|
158
|
+
return ['systemd-run', '--user', '--scope', '--quiet', '--collect', `--unit=harness-job-${name}-${process.pid}`,
|
|
159
|
+
'-p', `MemoryMax=${Math.round(l.procMem / 1048576)}M`, '-p', `CPUQuota=${l.procCpu}%`, '--', ...argv];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Kill a process group: TERM, then KILL after `grace` ms if anything is left. */
|
|
163
|
+
export function killGroup(pgid, grace = 5000) {
|
|
164
|
+
if (!pgid) return;
|
|
165
|
+
try { process.kill(-pgid, 'SIGTERM'); } catch { return; }
|
|
166
|
+
const t = setTimeout(() => { try { process.kill(-pgid, 'SIGKILL'); } catch { /* gone */ } }, grace);
|
|
167
|
+
t.unref?.();
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** One step: a shell line (cmd) or a structured argv (no shell), in its own process group. */
|
|
171
|
+
function runStep(ctx, job, step, env, log, redact) {
|
|
172
|
+
return new Promise((resolve) => {
|
|
173
|
+
const fd = fs.openSync(log, 'a');
|
|
174
|
+
const out = cappedWriter(fd, job.maxOutputBytes || 8 * 1024 * 1024, redact);
|
|
175
|
+
const argv = step.argv ? scoped(ctx, step.argv, job.id) : ['bash', '-lc', step.cmd];
|
|
176
|
+
let child;
|
|
177
|
+
try {
|
|
178
|
+
child = spawn(argv[0], argv.slice(1), { cwd: step.cwd || ctx.env.HOME, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
|
|
179
|
+
} catch (e) {
|
|
180
|
+
fs.writeSync(fd, `${e.message}\n`); fs.closeSync(fd); resolve({ code: 127 }); return;
|
|
181
|
+
}
|
|
182
|
+
job.pid = child.pid;
|
|
183
|
+
write(ctx, job);
|
|
184
|
+
child.stdout.on('data', (b) => out.write(b));
|
|
185
|
+
child.stderr.on('data', (b) => out.write(b));
|
|
186
|
+
let timer = null;
|
|
187
|
+
if (job.timeoutSeconds) {
|
|
188
|
+
const left = Math.max(1, job.timeoutSeconds * 1000 - (Date.now() - Date.parse(job.startedAt)));
|
|
189
|
+
timer = setTimeout(() => { job.timedOut = true; killGroup(child.pid, 3000); }, left);
|
|
190
|
+
}
|
|
191
|
+
child.on('error', (e) => { out.write(`${e.message}\n`); });
|
|
192
|
+
child.on('close', (code, signal) => {
|
|
193
|
+
if (timer) clearTimeout(timer);
|
|
194
|
+
job.outputBytes += out.end();
|
|
195
|
+
fs.closeSync(fd);
|
|
196
|
+
resolve({ code: code ?? (signal ? 128 + (signal === 'SIGKILL' ? 9 : 15) : 1), signal });
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Ask a running job to stop: its whole process tree is terminated; the runner records it as cancelled. */
|
|
202
|
+
export function cancelJob(ctx, id) {
|
|
203
|
+
const job = getJob(ctx, id);
|
|
204
|
+
if (!['queued', 'running'].includes(job.status)) return { id, status: job.status, note: 'already finished' };
|
|
205
|
+
job.cancelRequested = true;
|
|
206
|
+
write(ctx, job);
|
|
207
|
+
if (job.pid) killGroup(job.pid);
|
|
208
|
+
return { id, status: 'cancelling' };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** `harness-device job run <id>`: run the steps, record status. internals: { name: async (ctx, job, args) => void }. */
|
|
212
|
+
export async function runJob(ctx, id, internals = {}) {
|
|
213
|
+
const job = getJob(ctx, id);
|
|
214
|
+
const log = logOf(ctx, id);
|
|
215
|
+
const secrets = readSecrets(ctx.paths.secrets);
|
|
216
|
+
const token = job.tokenSecret ? secrets[job.tokenSecret] || null : null;
|
|
217
|
+
// Scoped env references: VAR ← device secret, injected for this job only, redacted from its output.
|
|
218
|
+
const refs = Object.entries(job.envRefs || {}).map(([v, name]) => [v, secrets[name]]).filter(([, val]) => typeof val === 'string' && val);
|
|
219
|
+
const hidden = [token, ...refs.map(([, val]) => val)].filter((x) => x && x.length >= 4);
|
|
220
|
+
const redact = (s) => hidden.reduce((acc, h) => acc.split(h).join('***'), s);
|
|
221
|
+
const env = { ...cleanEnv(ctx.env), ...gitAuthEnv(token), ...Object.fromEntries(refs), CI: '1' };
|
|
222
|
+
job.status = 'running';
|
|
223
|
+
job.startedAt = new Date().toISOString();
|
|
224
|
+
write(ctx, job);
|
|
225
|
+
const say = (m) => fs.appendFileSync(log, `\n[harness-device] ${m}\n`);
|
|
226
|
+
const builtins = { ...(await import('./project.js')).INTERNALS, ...internals };
|
|
227
|
+
try {
|
|
228
|
+
for (const [i, s] of job.steps.entries()) {
|
|
229
|
+
job.step = i;
|
|
230
|
+
write(ctx, job);
|
|
231
|
+
say(`step ${i + 1}/${job.steps.length}: ${s.name}${s.cmd ? `: ${redact(s.cmd)}` : ''}`);
|
|
232
|
+
if (s.internal) {
|
|
233
|
+
if (!builtins[s.internal]) throw new Error(`unknown internal step ${s.internal}`);
|
|
234
|
+
await builtins[s.internal](ctx, job, s.args || {});
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
if (getJob(ctx, id).cancelRequested) { job.cancelRequested = true; throw new Error('cancelled'); }
|
|
238
|
+
const { code } = await runStep(ctx, job, s, env, log, redact);
|
|
239
|
+
job.cancelRequested = getJob(ctx, id).cancelRequested;
|
|
240
|
+
job.exit = code;
|
|
241
|
+
if (job.cancelRequested) throw new Error('cancelled');
|
|
242
|
+
if (job.timedOut) throw new Error(`timed out after ${job.timeoutSeconds}s`);
|
|
243
|
+
if (code !== 0) throw new Error(`"${s.name}" exited with ${code}`);
|
|
244
|
+
}
|
|
245
|
+
job.status = 'done';
|
|
246
|
+
job.exit = 0;
|
|
247
|
+
say('done');
|
|
248
|
+
} catch (e) {
|
|
249
|
+
job.cancelled = !!job.cancelRequested;
|
|
250
|
+
job.status = job.cancelled ? 'cancelled' : 'failed';
|
|
251
|
+
job.error = redact(String(e.message || e));
|
|
252
|
+
say(`${job.status}: ${job.error}`);
|
|
253
|
+
}
|
|
254
|
+
job.pid = null;
|
|
255
|
+
job.finishedAt = new Date().toISOString();
|
|
256
|
+
write(ctx, job);
|
|
257
|
+
if (job.kind === 'exec') {
|
|
258
|
+
const { event } = await import('./state.js');
|
|
259
|
+
const s0 = job.steps[0] || {};
|
|
260
|
+
const secs = Math.round((Date.parse(job.finishedAt) - Date.parse(job.startedAt)) / 1000);
|
|
261
|
+
event(ctx, `exec ${job.id}: ${s0.argv ? path.basename(s0.argv[0]) : 'shell'} in ${job.app || '?'} → ${job.status}${job.exit !== null ? ` (exit ${job.exit})` : ''}, ${secs}s, ${job.outputBytes} bytes out`);
|
|
262
|
+
}
|
|
263
|
+
return job;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Status plus the end of the log, for job_status. */
|
|
267
|
+
export function describeJob(ctx, job, lines = 80) {
|
|
268
|
+
return { ...job, log: tail(logOf(ctx, job.id), lines) };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Stream a job's log: the bytes from `offset` on (at most `max`), and where to continue. */
|
|
272
|
+
export function readLog(ctx, id, offset = 0, max = 64 * 1024) {
|
|
273
|
+
const f = logOf(ctx, id);
|
|
274
|
+
if (!fs.existsSync(f)) return { data: '', next: 0, size: 0 };
|
|
275
|
+
const size = fs.statSync(f).size;
|
|
276
|
+
const from = Math.max(0, Math.min(Number(offset) || 0, size));
|
|
277
|
+
const len = Math.min(max, size - from);
|
|
278
|
+
const buf = Buffer.alloc(len);
|
|
279
|
+
const fd = fs.openSync(f, 'r');
|
|
280
|
+
try { fs.readSync(fd, buf, 0, len, from); } finally { fs.closeSync(fd); }
|
|
281
|
+
return { data: buf.toString('utf8'), next: from + len, size };
|
|
282
|
+
}
|
package/src/limits.js
CHANGED
|
@@ -140,6 +140,15 @@ export function groups(ctx, procs = parsePs(capture('ps', ['-A', '-o', 'pid=,ppi
|
|
|
140
140
|
out.push({ name: win, kind: 'session', pids: tree(procs, Number(pid)) });
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
|
+
// Running jobs (exec, setup, deploy…): each process group is held to the per-process caps.
|
|
144
|
+
const jobsDir = path.join(ctx.paths.state, 'jobs');
|
|
145
|
+
if (fs.existsSync(jobsDir)) {
|
|
146
|
+
for (const f of fs.readdirSync(jobsDir).filter((x) => x.endsWith('.json'))) {
|
|
147
|
+
let j;
|
|
148
|
+
try { j = JSON.parse(fs.readFileSync(path.join(jobsDir, f), 'utf8')); } catch { continue; }
|
|
149
|
+
if (j.status === 'running' && j.pid && procs.has(j.pid)) out.push({ name: `job-${j.id}`, kind: 'job', pids: tree(procs, j.pid), jobId: j.id });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
143
152
|
const port = `--remote-debugging-port=${ctx.cfg.CDP_PORT}`;
|
|
144
153
|
const roots = [...procs.values()].filter((p) => p.args.includes(port) && !(procs.get(p.ppid)?.args || '').includes(port));
|
|
145
154
|
if (roots.length) out.push({ name: 'browser', kind: 'browser', pids: roots.flatMap((r) => tree(procs, r.pid)) });
|
|
@@ -167,7 +176,7 @@ export function decide(gs, l, prev = {}, now = Date.now()) {
|
|
|
167
176
|
if (g.kind === 'session') continue;
|
|
168
177
|
const memMax = g.kind === 'browser' ? l.browserMem : l.procMem;
|
|
169
178
|
const memOver = g.rss > memMax;
|
|
170
|
-
const cpuOver = g.kind === 'proc' && g.cpuPct !== null && g.cpuPct > l.procCpu;
|
|
179
|
+
const cpuOver = (g.kind === 'proc' || g.kind === 'job') && g.cpuPct !== null && g.cpuPct > l.procCpu;
|
|
171
180
|
if (over(g.name, memOver || cpuOver)) {
|
|
172
181
|
actions.push({ name: g.name, kind: g.kind, reason: memOver ? `using ${humanMem(g.rss)}, limit ${humanMem(memMax)}` : `using ${g.cpuPct}% CPU, limit ${l.procCpu}%` });
|
|
173
182
|
}
|
|
@@ -203,7 +212,7 @@ export async function enforce(ctx, { act = true } = {}) {
|
|
|
203
212
|
const { event } = await import('./state.js');
|
|
204
213
|
for (const a of actions) {
|
|
205
214
|
const g = gs.find((x) => x.name === a.name);
|
|
206
|
-
event(ctx, `limits: stopped ${a.name} (${a.reason})${a.kind === 'proc' ? '; it restarts with backoff' : ''}`);
|
|
215
|
+
event(ctx, `limits: stopped ${a.name} (${a.reason})${a.kind === 'proc' ? '; it restarts with backoff' : a.kind === 'job' ? '; the job fails (it is not restarted)' : ''}`);
|
|
207
216
|
if (a.kind === 'browser') {
|
|
208
217
|
const { restartService } = await import('./device.js');
|
|
209
218
|
try { restartService(ctx, 'chromium'); } catch { stopTree(g.pids); }
|
package/src/mcp/server.js
CHANGED
|
@@ -16,6 +16,9 @@ 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';
|
|
21
|
+
import * as execMod from '../exec.js';
|
|
19
22
|
import { Cancelled, NeedsUser, interaction } from './interact.js';
|
|
20
23
|
|
|
21
24
|
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
@@ -107,6 +110,96 @@ export function buildServer(env = process.env, opts = {}) {
|
|
|
107
110
|
return text(`proc ${a.name} removed`);
|
|
108
111
|
});
|
|
109
112
|
|
|
113
|
+
// ---- Managed apps (src/project.js): clone, set up, run, update ---------------------------
|
|
114
|
+
const APP = z.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/).describe('app name (app_list); a session project name works too');
|
|
115
|
+
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}"}` });
|
|
116
|
+
|
|
117
|
+
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.', {},
|
|
118
|
+
async (c) => text(project.list(c)));
|
|
119
|
+
|
|
120
|
+
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.',
|
|
121
|
+
{ 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(),
|
|
122
|
+
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 },
|
|
123
|
+
async (c, a) => {
|
|
124
|
+
await guard(c, a, `cloning ${a.url}`);
|
|
125
|
+
return jobReply(await project.clone(c, { url: a.url, name: a.name, branch: a.branch, tokenSecret: a.token_secret, session: a.session }), 'The clone');
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
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.',
|
|
129
|
+
{ app: APP, ...FORCE },
|
|
130
|
+
async (c, a) => { await guard(c, a, `pulling ${a.app}`); return jobReply(await project.pull(c, { app: a.app }), 'The pull'); });
|
|
131
|
+
|
|
132
|
+
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.',
|
|
133
|
+
{ app: APP, ...FORCE },
|
|
134
|
+
async (c, a) => {
|
|
135
|
+
await guard(c, a, `setting up ${a.app}`);
|
|
136
|
+
const r = await project.setup(c, { app: a.app });
|
|
137
|
+
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 }) });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
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.',
|
|
141
|
+
{ 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 },
|
|
142
|
+
async (c, a) => { await guard(c, a, `starting ${a.app}`); return text(project.start(c, { app: a.app, command: a.command, port: a.port })); });
|
|
143
|
+
|
|
144
|
+
tool('project_stop', 'Stop an app\'s process (asks the user first). The app and its files stay; project_start runs it again.',
|
|
145
|
+
{ app: APP, ...CONFIRM },
|
|
146
|
+
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 })); });
|
|
147
|
+
|
|
148
|
+
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.',
|
|
149
|
+
{ app: APP, ...FORCE },
|
|
150
|
+
async (c, a) => { await guard(c, a, `deploying ${a.app}`); return jobReply(await project.deploy(c, { app: a.app }), 'The deploy'); });
|
|
151
|
+
|
|
152
|
+
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.',
|
|
153
|
+
{ app: APP, command: z.string().min(1).max(4000), timeout_seconds: z.number().int().min(1).max(3600).optional(), background: z.boolean().optional(), ...FORCE },
|
|
154
|
+
async (c, a) => {
|
|
155
|
+
await guard(c, a, 'a shell command');
|
|
156
|
+
const r = await project.shellExec(c, { app: a.app, command: a.command, timeoutSeconds: a.timeout_seconds, background: a.background });
|
|
157
|
+
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}` }] };
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
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).',
|
|
161
|
+
{ 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() },
|
|
162
|
+
async (c, a) => text(project.fileRead(c, { app: a.app, path: a.path, offset: a.offset, limit: a.limit })));
|
|
163
|
+
|
|
164
|
+
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).',
|
|
165
|
+
{ app: APP, path: z.string().min(1).max(500), content: z.string(), mode: z.enum(['overwrite', 'append', 'create']).optional() },
|
|
166
|
+
async (c, a) => text(project.fileWrite(c, { app: a.app, path: a.path, content: a.content, mode: a.mode })));
|
|
167
|
+
|
|
168
|
+
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.',
|
|
169
|
+
{ 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(),
|
|
170
|
+
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 },
|
|
171
|
+
async (c, a, u) => {
|
|
172
|
+
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})` : ''}?`);
|
|
173
|
+
return text(project.envManage(c, { app: a.app, action: a.action, key: a.key, value: a.value, fromSecret: a.from_secret, file: a.file }));
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
tool('exec', `Run one program in an app folder, without a shell: argv is [program, ...args], the program a bare name on this device's allowlist (${execMod.allowList(base.cfg).join(', ')}). Shells and wrappers (bash, sh, env, sudo, xargs…) are never allowed here; use shell_exec (device:admin) for shell syntax. Optional cwd (a sub-folder of the app), env_refs {VAR: DEVICE_SECRET} (injected for this run, redacted from output), timeout_seconds (default 600, max 3600), max_output_kb (default 256: first and last halves kept). It is a durable job: waits up to wait_seconds (default 30, max 120) and returns the exit code and output, or the job id to follow with job_status (offset streams new output) and stop with job_cancel. Never restarted.`,
|
|
177
|
+
{ app: APP, argv: z.array(z.string().max(8000)).min(1).max(200), cwd: z.string().max(500).optional(), env_refs: z.record(z.string(), z.string()).optional(),
|
|
178
|
+
timeout_seconds: z.number().int().min(1).max(3600).optional(), max_output_kb: z.number().int().min(1).max(4096).optional(), wait_seconds: z.number().int().min(0).max(120).optional(), ...FORCE },
|
|
179
|
+
async (c, a) => {
|
|
180
|
+
await guard(c, a, `running ${a.argv[0]}`);
|
|
181
|
+
const job = await execMod.exec(c, { app: a.app, argv: a.argv, cwd: a.cwd, envRefs: a.env_refs, timeoutSeconds: a.timeout_seconds, maxOutputKb: a.max_output_kb, waitSeconds: a.wait_seconds ?? 30 });
|
|
182
|
+
const done = !['queued', 'running'].includes(job.status);
|
|
183
|
+
const log = jobs.readLog(c, job.id, 0, 256 * 1024);
|
|
184
|
+
const body = { job: job.id, status: job.status, exit: job.exit, timed_out: job.timedOut, cancelled: job.cancelled, output_bytes: job.outputBytes,
|
|
185
|
+
output: log.data.replace(/^\n?\[harness-device\] step 1\/1: [^\n]*\n/, '').replace(/\n\[harness-device\] (done|failed|cancelled)[^\n]*\n?$/, ''),
|
|
186
|
+
...(done ? {} : { next: `still running: job_status {"id":"${job.id}","offset":${log.next}} for new output, job_cancel to stop it` }) };
|
|
187
|
+
return { ...(done && job.status !== 'done' ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(body, null, 2) }] };
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
tool('job_cancel', 'Stop a running job (exec, clone, setup, deploy…): its whole process tree is terminated (TERM, then KILL after 5s); the job ends as cancelled.',
|
|
191
|
+
{ id: z.string().regex(/^[a-z0-9-]{6,40}$/) },
|
|
192
|
+
async (c, a) => text(jobs.cancelJob(c, a.id)));
|
|
193
|
+
|
|
194
|
+
tool('job_status', 'A background job (exec, clone, setup, pull, deploy, long shell command): status, current step, exit code and the end of its log. With offset: the log bytes from there on and the next offset (stream the output). Without id: recent jobs.',
|
|
195
|
+
{ id: z.string().regex(/^[a-z0-9-]{6,40}$/).optional(), lines: z.number().int().min(1).max(500).optional(), offset: z.number().int().min(0).optional() },
|
|
196
|
+
async (c, a) => {
|
|
197
|
+
if (!a.id) return text(jobs.listJobs(c).map(({ steps, ...j }) => j));
|
|
198
|
+
const job = jobs.getJob(c, a.id);
|
|
199
|
+
if (a.offset !== undefined) { const { steps, ...j } = job; return text({ ...j, ...jobs.readLog(c, a.id, a.offset) }); }
|
|
200
|
+
return text(jobs.describeJob(c, job, a.lines || 80));
|
|
201
|
+
});
|
|
202
|
+
|
|
110
203
|
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
204
|
async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
|
|
112
205
|
|
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,12 @@ 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
|
+
'exec', 'job_cancel'],
|
|
19
|
+
// shell_exec is not listed: it needs device:admin (unknown tools do).
|
|
16
20
|
};
|
|
17
21
|
|
|
18
22
|
/** 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
|
+
}
|