@dreamtree-org/harness-device 0.3.0 → 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 +7 -0
- package/package.json +1 -1
- package/src/capabilities.js +2 -1
- package/src/config.js +4 -0
- package/src/exec.js +77 -0
- package/src/jobs.js +165 -24
- package/src/limits.js +11 -2
- package/src/mcp/server.js +27 -3
- package/src/serve/scopes.js +2 -1
package/README.md
CHANGED
|
@@ -206,9 +206,16 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
|
|
|
206
206
|
| `git_pull` | Updates only. It refuses when there are uncommitted changes |
|
|
207
207
|
| `file_read` / `file_write` | Inside the app folder only; `.git` and `.env` are off limits |
|
|
208
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) |
|
|
209
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` |
|
|
210
211
|
| `job_status` (`job <id>`) | Status, step and the end of the log for clone, setup, pull, deploy and long commands |
|
|
211
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
|
+
|
|
212
219
|
### Join a pool (HarnessPro)
|
|
213
220
|
|
|
214
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/capabilities.js
CHANGED
|
@@ -111,7 +111,8 @@ Apps are repositories this device runs, in \`${cfg.APPS_DIR || '~/apps'}\`; unli
|
|
|
111
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
112
|
- Jobs run in the background: follow them with \`job_status\`, don't wait in a loop without telling the user.
|
|
113
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
|
-
- \`
|
|
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.
|
|
115
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.
|
|
116
117
|
|
|
117
118
|
## Device, disk and services
|
package/src/config.js
CHANGED
|
@@ -100,6 +100,9 @@ export function defaults(env = process.env) {
|
|
|
100
100
|
POOL_SCOPES: 'device:read,device:operate',
|
|
101
101
|
// Where git_clone puts managed apps (empty = ~/apps).
|
|
102
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: '',
|
|
103
106
|
};
|
|
104
107
|
}
|
|
105
108
|
|
|
@@ -212,6 +215,7 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
212
215
|
if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
|
|
213
216
|
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
214
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.');
|
|
215
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.');
|
|
216
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.');
|
|
217
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.');
|
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
CHANGED
|
@@ -11,9 +11,10 @@
|
|
|
11
11
|
import crypto from 'node:crypto';
|
|
12
12
|
import fs from 'node:fs';
|
|
13
13
|
import path from 'node:path';
|
|
14
|
-
import { spawn } from 'node:child_process';
|
|
14
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
15
15
|
import { readSecrets } from './context.js';
|
|
16
|
-
import { PKG_ROOT } from './util.js';
|
|
16
|
+
import { PKG_ROOT, which } from './util.js';
|
|
17
|
+
import { limits as computeLimits } from './limits.js';
|
|
17
18
|
|
|
18
19
|
const KEEP = 50;
|
|
19
20
|
const dirOf = (ctx) => path.join(ctx.paths.state, 'jobs');
|
|
@@ -61,18 +62,40 @@ export function tail(file, lines = 80) {
|
|
|
61
62
|
* tokenSecret: the name of a device secret git may use for https://github.com.
|
|
62
63
|
* Returns the job.
|
|
63
64
|
*/
|
|
64
|
-
export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false }) {
|
|
65
|
+
export function startJob(ctx, { kind, app = null, steps, tokenSecret = null, inline = false, timeoutSeconds = null, maxOutputBytes = null, envRefs = null }) {
|
|
65
66
|
const id = `${kind}-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`.toLowerCase();
|
|
66
|
-
const job = {
|
|
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
|
+
};
|
|
67
73
|
write(ctx, job);
|
|
68
74
|
prune(ctx);
|
|
69
75
|
fs.mkdirSync(path.dirname(logOf(ctx, id)), { recursive: true });
|
|
70
76
|
if (inline || ctx.env.HD_JOBS_INLINE === '1') return runJob(ctx, id).then(() => getJob(ctx, id));
|
|
71
77
|
const bin = path.join(PKG_ROOT, 'bin', 'harness-device.js');
|
|
72
|
-
|
|
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
|
+
}
|
|
73
89
|
return Promise.resolve(job);
|
|
74
90
|
}
|
|
75
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
|
+
|
|
76
99
|
/** Git auth through the environment only (GIT_CONFIG_*), for https://github.com. */
|
|
77
100
|
export function gitAuthEnv(token) {
|
|
78
101
|
if (!token) return {};
|
|
@@ -80,27 +103,122 @@ export function gitAuthEnv(token) {
|
|
|
80
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' };
|
|
81
104
|
}
|
|
82
105
|
|
|
83
|
-
|
|
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) {
|
|
84
172
|
return new Promise((resolve) => {
|
|
85
173
|
const fd = fs.openSync(log, 'a');
|
|
86
|
-
const out =
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
+
});
|
|
93
198
|
});
|
|
94
199
|
}
|
|
95
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
|
+
|
|
96
211
|
/** `harness-device job run <id>`: run the steps, record status. internals: { name: async (ctx, job, args) => void }. */
|
|
97
212
|
export async function runJob(ctx, id, internals = {}) {
|
|
98
213
|
const job = getJob(ctx, id);
|
|
99
214
|
const log = logOf(ctx, id);
|
|
100
|
-
const
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
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' };
|
|
104
222
|
job.status = 'running';
|
|
105
223
|
job.startedAt = new Date().toISOString();
|
|
106
224
|
write(ctx, job);
|
|
@@ -116,22 +234,32 @@ export async function runJob(ctx, id, internals = {}) {
|
|
|
116
234
|
await builtins[s.internal](ctx, job, s.args || {});
|
|
117
235
|
continue;
|
|
118
236
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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}`);
|
|
124
244
|
}
|
|
125
245
|
job.status = 'done';
|
|
126
246
|
job.exit = 0;
|
|
127
247
|
say('done');
|
|
128
248
|
} catch (e) {
|
|
129
|
-
job.
|
|
249
|
+
job.cancelled = !!job.cancelRequested;
|
|
250
|
+
job.status = job.cancelled ? 'cancelled' : 'failed';
|
|
130
251
|
job.error = redact(String(e.message || e));
|
|
131
|
-
say(
|
|
252
|
+
say(`${job.status}: ${job.error}`);
|
|
132
253
|
}
|
|
254
|
+
job.pid = null;
|
|
133
255
|
job.finishedAt = new Date().toISOString();
|
|
134
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
|
+
}
|
|
135
263
|
return job;
|
|
136
264
|
}
|
|
137
265
|
|
|
@@ -139,3 +267,16 @@ export async function runJob(ctx, id, internals = {}) {
|
|
|
139
267
|
export function describeJob(ctx, job, lines = 80) {
|
|
140
268
|
return { ...job, log: tail(logOf(ctx, job.id), lines) };
|
|
141
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
|
@@ -18,6 +18,7 @@ import * as cleanup from '../cleanup.js';
|
|
|
18
18
|
import * as limits from '../limits.js';
|
|
19
19
|
import * as project from '../project.js';
|
|
20
20
|
import * as jobs from '../jobs.js';
|
|
21
|
+
import * as execMod from '../exec.js';
|
|
21
22
|
import { Cancelled, NeedsUser, interaction } from './interact.js';
|
|
22
23
|
|
|
23
24
|
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
@@ -172,9 +173,32 @@ export function buildServer(env = process.env, opts = {}) {
|
|
|
172
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 }));
|
|
173
174
|
});
|
|
174
175
|
|
|
175
|
-
tool('
|
|
176
|
-
{
|
|
177
|
-
|
|
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
|
+
});
|
|
178
202
|
|
|
179
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.', {},
|
|
180
204
|
async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
|
package/src/serve/scopes.js
CHANGED
|
@@ -14,7 +14,8 @@ const TOOLS = {
|
|
|
14
14
|
'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get',
|
|
15
15
|
'app_list', 'file_read', 'job_status'],
|
|
16
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'
|
|
17
|
+
'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
|
|
18
|
+
'exec', 'job_cancel'],
|
|
18
19
|
// shell_exec is not listed: it needs device:admin (unknown tools do).
|
|
19
20
|
};
|
|
20
21
|
|