@dreamtree-org/harness-device 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/README.md +16 -1
- package/package.json +1 -1
- package/sh/bin/hd-gate-hook +6 -0
- package/sh/bin/hd-heal +23 -0
- package/src/capabilities.js +9 -0
- package/src/cli.js +84 -4
- package/src/config.js +27 -1
- package/src/device.js +3 -3
- package/src/install.js +3 -2
- package/src/mcp/server.js +30 -2
- package/src/platform/darwin.js +14 -0
- package/src/platform/linux.js +18 -1
- package/src/providers/claude.js +26 -3
- package/src/resources.js +168 -0
- package/src/upgrade.js +151 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.4
|
|
4
|
+
|
|
5
|
+
- **Upgrades without downtime:** `harness-device upgrade [--check] [--to x.y.z]` and an `upgrade` MCP tool (approved in the session). The new version installs next to the running copy, is verified, swapped in, and applied gracefully: only changed services restart, tmux and its sessions never do. A failure rolls back to the previous copy. Automatic every `AUTO_UPGRADE_HOURS` (6) within `AUTO_UPGRADE` (`minor` by default; `patch`, `all`, `off`); deferred while the device is busy; never for source-folder installs.
|
|
6
|
+
- **Resource guard (CPU, RAM, disk):** new work waits while the device is critical and is refused if it stays critical; forcing is refused while critical. It applies to `proc add`, `session new`, test runs, Playwright UI, and the agent's shell commands through a Claude Code `PreToolUse` hook on Bash (light commands like `ps`, `kill`, `docker prune` always pass; the hook fails open). `harness-device resources`, the `resources` MCP tool (pre-approved), resources in `status` and `device_status`, and `events` entries when the device enters or leaves critical. Settings: `RESOURCE_GUARD`, `RES_WAIT_SECONDS`, `RES_CPU_CRITICAL`, `RES_MEM_CRITICAL`, `RES_DISK_CRITICAL`.
|
|
7
|
+
- **Graceful activation on Linux:** `install --graceful` restarts only services whose unit changed (macOS already did).
|
|
8
|
+
|
|
3
9
|
## 0.1.3
|
|
4
10
|
|
|
5
11
|
Remote first: everything a session does on the device, you approve from the session; nothing needs you at the machine, and the session never edits the device's own files.
|
package/README.md
CHANGED
|
@@ -127,7 +127,22 @@ Secrets in Dokploy's API responses (env vars, passwords, tokens) are redacted be
|
|
|
127
127
|
|
|
128
128
|
### Updating
|
|
129
129
|
|
|
130
|
-
|
|
130
|
+
**Automatic, no downtime.** Every `AUTO_UPGRADE_HOURS` (default 6) the heal job checks npm. A newer version within `AUTO_UPGRADE` (`patch`, `minor` by default, `all`, or `off`) is installed next to the running copy, checked, swapped in, and applied by the new version in graceful mode:
|
|
131
|
+
- scripts are replaced atomically
|
|
132
|
+
- only services whose definitions changed are restarted
|
|
133
|
+
- the tmux service, which holds every agent session, is never restarted
|
|
134
|
+
|
|
135
|
+
If anything fails, the previous version is swapped back. Upgrades wait while the device is busy, and devices installed from a source folder are never auto-upgraded. History: `harness-device events`; output: `harness-device logs upgrade`.
|
|
136
|
+
|
|
137
|
+
**By hand:** `harness-device upgrade --check`, then `harness-device upgrade` (or `--to x.y.z`). Sessions get the new device tools when they next restart. A remote session can do it through the `upgrade` tool, which you approve. `npx @dreamtree-org/harness-device@latest install` still works and is idempotent. Add or drop capabilities with `init --with …` / `--without …`, then `install`.
|
|
138
|
+
|
|
139
|
+
### Resource guard
|
|
140
|
+
|
|
141
|
+
New work from a session waits while CPU, RAM or disk is critical, and is refused if the device stays critical. This covers registered processes, test runs, Playwright UI, new sessions, and the agent's shell commands (through a Claude Code hook on Bash).
|
|
142
|
+
- Commands that only look or free resources always run: `ps`, `df`, `kill`, `docker stop`/`prune`, `rm`, `harness-device status`/`resources`/`proc rm`.
|
|
143
|
+
- Forcing (`force`, `--force`, `HD_FORCE=1`) skips the wait, and is refused outright while the device is critical.
|
|
144
|
+
- Check it with `harness-device resources`. Tune it with `config set`: `RES_WAIT_SECONDS` (300), `RES_CPU_CRITICAL` (95% busy), `RES_MEM_CRITICAL` (5% available), `RES_DISK_CRITICAL` (3% free, or under 1 GiB), `RESOURCE_GUARD=off`.
|
|
145
|
+
- The heal job records every move into or out of critical in `events`.
|
|
131
146
|
|
|
132
147
|
## Commands
|
|
133
148
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreamtree-org/harness-device",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
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",
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Claude Code PreToolUse hook (Bash): the device's resource guard. Reads the
|
|
3
|
+
# hook JSON on stdin; prints a deny decision only when the device is critical.
|
|
4
|
+
# Any failure lets the command through.
|
|
5
|
+
. "$(dirname "$0")/hd-lib.sh" 2>/dev/null || exit 0
|
|
6
|
+
exec "$HD_HOME/bin/harness-device" gate --hook || exit 0
|
package/sh/bin/hd-heal
CHANGED
|
@@ -31,3 +31,26 @@ else
|
|
|
31
31
|
hd_log "tmux session $HD_SESSION is gone; restarting harness-tmux"
|
|
32
32
|
hd_svc_restart harness-tmux || true
|
|
33
33
|
fi
|
|
34
|
+
# Resources: record when the device crosses into or out of critical (the
|
|
35
|
+
# guard makes new work wait meanwhile; this leaves a trail for `events`).
|
|
36
|
+
lvl=$("$HD_HOME/bin/harness-device" resources --json 2>/dev/null | sed -n 's/^ "level": "\([a-z]*\)".*/\1/p' | head -1)
|
|
37
|
+
prev=$(cat "$HD_STATE/resource-level" 2>/dev/null || echo ok)
|
|
38
|
+
if [ -n "$lvl" ] && [ "$lvl" != "$prev" ]; then
|
|
39
|
+
mkdir -p "$HD_STATE"; echo "$lvl" > "$HD_STATE/resource-level"
|
|
40
|
+
if [ "$lvl" = critical ] || [ "$prev" = critical ]; then
|
|
41
|
+
hd_event "resources $prev → $lvl: $("$HD_HOME/bin/harness-device" resources 2>/dev/null | head -1)"
|
|
42
|
+
fi
|
|
43
|
+
fi
|
|
44
|
+
# Automatic upgrades from npm, at most every AUTO_UPGRADE_HOURS. The check runs
|
|
45
|
+
# here; the upgrade itself runs detached (it may reload this very job).
|
|
46
|
+
if [ "${HD_AUTO_UPGRADE:-off}" != off ]; then
|
|
47
|
+
due=$(cat "$HD_STATE/upgrade-due" 2>/dev/null || echo 0)
|
|
48
|
+
now=$(date +%s)
|
|
49
|
+
case "$due" in ''|*[!0-9]*) due=0 ;; esac
|
|
50
|
+
if [ "$now" -ge "$due" ]; then
|
|
51
|
+
mkdir -p "$HD_STATE"
|
|
52
|
+
echo $(( now + ${HD_AUTO_UPGRADE_HOURS:-6} * 3600 )) > "$HD_STATE/upgrade-due"
|
|
53
|
+
mkdir -p "$HD_HOME/logs"
|
|
54
|
+
"$HD_HOME/bin/harness-device" upgrade --auto --detach >> "$HD_HOME/logs/upgrade.log" 2>&1 || hd_log "upgrade check failed (logs/upgrade.log)"
|
|
55
|
+
fi
|
|
56
|
+
fi
|
package/src/capabilities.js
CHANGED
|
@@ -83,6 +83,15 @@ The user is usually remote (phone, claude.ai) and can't type on this machine. Ev
|
|
|
83
83
|
- Long-running processes: \`proc_add\` / \`proc_remove\`. Public URLs: \`ngrok_up\` / \`ngrok_down\`.
|
|
84
84
|
- Put your own files (test pages, scripts, data) in the project folder, never in the device home.
|
|
85
85
|
- **Don't ask the user to run commands on the machine** (no \`! ...\` instructions). If no tool covers what you need, say what is missing.
|
|
86
|
+
|
|
87
|
+
### CPU, RAM and disk come first
|
|
88
|
+
The device guards its resources. Before heavy work (builds, test runs, containers, big installs, model downloads) check \`resources\` (MCP) or \`harness-device resources\`.
|
|
89
|
+
- While CPU, RAM or disk is **critical**, new work waits for it to recover (up to RES_WAIT_SECONDS), then is refused: registered processes, test runs, Playwright UI, new sessions, and your shell commands (a hook on Bash). Commands that only look or free resources (ps, df, du, kill, docker stop/prune, rm, harness-device status/resources/proc rm, ...) always run.
|
|
90
|
+
- \`force\` (or \`HD_FORCE=1\` in front of a shell command) skips the wait, and is **refused** while the device is critical: forcing never runs work on top of a critical device. If the user insists, explain what is using the resources and offer to free them (stop a process, prune Docker, clear caches) instead.
|
|
91
|
+
- When it is only **high**, go ahead but prefer one heavy job at a time.
|
|
92
|
+
|
|
93
|
+
### Upgrades
|
|
94
|
+
harness-device upgrades itself from npm (AUTO_UPGRADE, default minor) without stopping sessions or unchanged services. \`upgrade\` with check=true shows what is available; a newer version applies to this session's device tools when the session next restarts.
|
|
86
95
|
- Only three things need the machine itself (local or SSH): entering secrets (\`harness-device secrets set\`), \`harness-device init/install\` (capabilities, projects, upgrades) and the first \`claude\` login. Those commands are denied to you.`,
|
|
87
96
|
},
|
|
88
97
|
|
package/src/cli.js
CHANGED
|
@@ -12,6 +12,8 @@ import * as device from './device.js';
|
|
|
12
12
|
import * as state from './state.js';
|
|
13
13
|
import * as ngrok from './ngrok.js';
|
|
14
14
|
import * as fleet from './fleet.js';
|
|
15
|
+
import * as resources from './resources.js';
|
|
16
|
+
import * as upgrader from './upgrade.js';
|
|
15
17
|
import { PKG, log, color, run, writeFile, capture } from './util.js';
|
|
16
18
|
|
|
17
19
|
const HELP = `${color.bold('harness-device')} ${PKG.version}: a reboot-proof dev device for remote AI agents (Claude Remote Control first)
|
|
@@ -43,6 +45,9 @@ ${color.bold('Device')}
|
|
|
43
45
|
config get [KEY] | set KEY=VALUE settings a remote session may change (ngrok, Dokploy filters, transcript days)
|
|
44
46
|
ngrok token | up [viewers|apps|all|<tunnel>]... [--port 8099] | down | status
|
|
45
47
|
restart <service> restart one harness service (chromium, ttyd, ...)
|
|
48
|
+
resources [--json] CPU, RAM and disk now, with the guard's level (ok, high, critical)
|
|
49
|
+
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
50
|
+
upgrade [--check] [--to x.y.z] upgrade from npm without stopping sessions (AUTO_UPGRADE does it on its own)
|
|
46
51
|
mcp run the harness-device MCP server (stdio)
|
|
47
52
|
|
|
48
53
|
${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
@@ -53,8 +58,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
53
58
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
54
59
|
`;
|
|
55
60
|
|
|
56
|
-
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'json', 'purge', 'force', 'follow', 'help', 'version'];
|
|
57
|
-
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port'];
|
|
61
|
+
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook'];
|
|
62
|
+
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait'];
|
|
58
63
|
|
|
59
64
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
60
65
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -124,6 +129,11 @@ function setSecret(file, key, value) {
|
|
|
124
129
|
|
|
125
130
|
function printStatus(s) {
|
|
126
131
|
console.log(`${color.bold(s.device)} ${color.dim(`· ${s.provider} · ${s.serveMode} mode · ${s.capabilities.join(', ')}`)}`);
|
|
132
|
+
if (s.resources) {
|
|
133
|
+
const r = s.resources;
|
|
134
|
+
const paint = r.level === 'critical' ? color.red : r.level === 'high' ? color.yellow : color.green;
|
|
135
|
+
console.log(`${paint(resources.summary(r))}${r.reasons.length ? color.dim(`\n ${r.reasons.join('\n ')}`) : ''}`);
|
|
136
|
+
}
|
|
127
137
|
console.log(color.bold('\nsessions'));
|
|
128
138
|
if (!s.sessions.length) console.log(color.dim(' none (harness-device project add name:/dir)'));
|
|
129
139
|
for (const x of s.sessions) {
|
|
@@ -139,7 +149,6 @@ function printStatus(s) {
|
|
|
139
149
|
console.log(' ' + s.services.map((x) => `${x.state === 'active' ? color.green('●') : color.red('○')} ${x.unit.replace(/^harness-/, '')}`).join(' '));
|
|
140
150
|
console.log(color.bold('\nviewers') + color.dim(' (127.0.0.1; harness-device tunnel)'));
|
|
141
151
|
console.log(` display ${s.viewers.display}\n tmux ${s.viewers.tmux}`);
|
|
142
|
-
console.log(`\n${color.dim(s.load)}`);
|
|
143
152
|
if (s.browser) console.log(color.dim(`browser: ${s.browser}`));
|
|
144
153
|
}
|
|
145
154
|
|
|
@@ -181,7 +190,54 @@ export async function main(argv) {
|
|
|
181
190
|
|
|
182
191
|
case 'install': {
|
|
183
192
|
const ctx = loadContext(env, { dryRun: !!f.dryRun });
|
|
184
|
-
return install(ctx, { skipSystem: !!f.skipSystem });
|
|
193
|
+
return install(ctx, { skipSystem: !!f.skipSystem, skipPkg: !!f.skipPkg, graceful: !!f.graceful });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
case 'upgrade': {
|
|
197
|
+
const ctx = loadContext(env);
|
|
198
|
+
const to = f.to && String(f.to);
|
|
199
|
+
if (to && !/^\d+\.\d+\.\d+$/.test(to)) throw new Error('--to takes a version such as 0.2.0');
|
|
200
|
+
if (f.check) {
|
|
201
|
+
const c = await upgrader.check(ctx, { to });
|
|
202
|
+
if (f.json) return console.log(JSON.stringify(c, null, 2));
|
|
203
|
+
console.log(`installed ${c.current} (${c.source}) · latest ${c.latest || '?'} · AUTO_UPGRADE=${c.policy}${c.available ? color.bold(' → update available') : ''}`);
|
|
204
|
+
if (c.note) console.log(color.dim(` ${c.note}`));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (f.detach) {
|
|
208
|
+
// From heal (or the MCP tool): check here, do the work outside every harness service.
|
|
209
|
+
const c = await upgrader.check(ctx, { to });
|
|
210
|
+
const go = f.auto ? c.autoAllowed : c.available && c.source === 'npm';
|
|
211
|
+
if (!go) return console.log(`no upgrade: ${c.note || `on ${c.current}, latest ${c.latest}`}`);
|
|
212
|
+
const bin = path.join(ctx.paths.bin, 'harness-device');
|
|
213
|
+
ctx.platform.spawnDetached(ctx, 'upgrade', [bin, 'upgrade', ...(f.auto ? ['--auto'] : []), '--to', c.latest], path.join(ctx.paths.logs, 'upgrade.log'));
|
|
214
|
+
return console.log(`upgrading ${c.current} → ${c.latest} in the background (harness-device logs upgrade)`);
|
|
215
|
+
}
|
|
216
|
+
const r = await upgrader.upgrade(ctx, { to, auto: !!f.auto, log: (m) => console.log(`[${new Date().toISOString()}] ${m}`.trimEnd()) });
|
|
217
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
218
|
+
return r.upgraded ? log.ok(`Upgraded ${r.from} → ${r.to}. ${r.note}`) : console.log(`no upgrade: ${r.note || `on ${r.current}, latest ${r.latest}`}`);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
case 'resources': {
|
|
222
|
+
const ctx = loadContext(env);
|
|
223
|
+
const s = await resources.sample(ctx);
|
|
224
|
+
return f.json ? console.log(JSON.stringify(s, null, 2)) : console.log(resources.summary(s) + (s.reasons.length ? `\n ${s.reasons.join('\n ')}` : ''));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
case 'gate': {
|
|
228
|
+
const ctx = loadContext(env);
|
|
229
|
+
if (f.hook) return gateHook(ctx);
|
|
230
|
+
try {
|
|
231
|
+
const r = await resources.gate(ctx, { force: !!f.force, waitSeconds: f.wait !== undefined ? Number(f.wait) : undefined, what: 'this command',
|
|
232
|
+
onWait: (s, t) => process.stderr.write(`device critical (${s.reasons.join('; ')}); waiting ${t}s…\n`) });
|
|
233
|
+
if (r.level === 'high') log.warn(`device busy: ${r.reasons.join('; ')}`);
|
|
234
|
+
return;
|
|
235
|
+
} catch (e) {
|
|
236
|
+
if (!(e instanceof resources.ResourceDenied)) throw e;
|
|
237
|
+
console.error(e.message);
|
|
238
|
+
process.exitCode = 3;
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
185
241
|
}
|
|
186
242
|
|
|
187
243
|
case 'uninstall':
|
|
@@ -231,6 +287,7 @@ export async function main(argv) {
|
|
|
231
287
|
return;
|
|
232
288
|
}
|
|
233
289
|
if (sub === 'new') {
|
|
290
|
+
await resources.gate(ctx, { force: !!f.force, what: 'a new session' });
|
|
234
291
|
const r = state.newSlot(ctx, rest[0]);
|
|
235
292
|
log.ok(`${rest[0]} slot ${r.slot}: conversation ${r.id} (window ${state.windowName(rest[0], r.slot)})`);
|
|
236
293
|
return state.applyLayout(ctx);
|
|
@@ -256,6 +313,7 @@ export async function main(argv) {
|
|
|
256
313
|
const [name, dir, ...cmdParts] = rest;
|
|
257
314
|
if (!cmdParts.length) throw new Error("usage: proc add <name> <dir> '<command>'");
|
|
258
315
|
guardOwn(ctx, `proc-${name}`, f);
|
|
316
|
+
await resources.gate(ctx, { force: !!f.force, what: `starting process ${name}`, onWait: (s, t) => process.stderr.write(`device critical (${s.reasons.join('; ')}); waiting ${t}s…\n`) });
|
|
259
317
|
state.addProc(ctx, name, path.resolve(dir), cmdParts.join(' '));
|
|
260
318
|
return log.ok(`proc ${name} registered; running in tmux window proc-${name}`);
|
|
261
319
|
}
|
|
@@ -400,3 +458,25 @@ export async function main(argv) {
|
|
|
400
458
|
throw new Error(`Unknown command "${cmd}". Run: harness-device help`);
|
|
401
459
|
}
|
|
402
460
|
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Claude Code PreToolUse hook (Bash): commands that only look or free
|
|
464
|
+
* resources pass at once; anything else waits while the device is critical and
|
|
465
|
+
* is refused if it stays critical (or if HD_FORCE=1 asks to skip the wait).
|
|
466
|
+
* Any error lets the command through: the guard must never wedge a session.
|
|
467
|
+
*/
|
|
468
|
+
async function gateHook(ctx) {
|
|
469
|
+
try {
|
|
470
|
+
const input = JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
|
|
471
|
+
const cmd = (input.tool_input && input.tool_input.command) || '';
|
|
472
|
+
if (resources.isLightCommand(cmd)) return;
|
|
473
|
+
const force = /(^|\s)HD_FORCE=1(\s|$)/.test(cmd);
|
|
474
|
+
try {
|
|
475
|
+
await resources.gate(ctx, { force, quick: true, waitSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 0, 540), what: 'this command' });
|
|
476
|
+
} catch (e) {
|
|
477
|
+
if (!(e instanceof resources.ResourceDenied)) return;
|
|
478
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
479
|
+
permissionDecisionReason: `${e.message} Check with: harness-device resources.` } }));
|
|
480
|
+
}
|
|
481
|
+
} catch { /* fail open */ }
|
|
482
|
+
}
|
package/src/config.js
CHANGED
|
@@ -63,6 +63,16 @@ export function defaults(env = process.env) {
|
|
|
63
63
|
NGROK_DOMAIN: '',
|
|
64
64
|
// Your existing Dokploy (e.g. https://dokploy.example.com); the device only uses its API.
|
|
65
65
|
DOKPLOY_URL: '',
|
|
66
|
+
// Upgrades from npm without stopping anything: off | patch | minor | all (how far
|
|
67
|
+
// the automatic check may go; `harness-device upgrade` goes to latest on request).
|
|
68
|
+
AUTO_UPGRADE: 'minor',
|
|
69
|
+
AUTO_UPGRADE_HOURS: '6',
|
|
70
|
+
// Resource guard: new work waits while CPU, RAM or disk is critical.
|
|
71
|
+
RESOURCE_GUARD: 'on',
|
|
72
|
+
RES_WAIT_SECONDS: '300',
|
|
73
|
+
RES_CPU_CRITICAL: '95',
|
|
74
|
+
RES_MEM_CRITICAL: '5',
|
|
75
|
+
RES_DISK_CRITICAL: '3',
|
|
66
76
|
};
|
|
67
77
|
}
|
|
68
78
|
|
|
@@ -170,6 +180,13 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
170
180
|
if (!['conversation', 'server'].includes(cfg.SERVE_MODE)) errs.push('SERVE_MODE must be conversation or server.');
|
|
171
181
|
if (!/^\d+$/.test(String(cfg.TRANSCRIPT_DAYS)) || Number(cfg.TRANSCRIPT_DAYS) < 30) errs.push('TRANSCRIPT_DAYS must be a number of days, at least 30.');
|
|
172
182
|
if (cfg.DOKPLOY_URL && !/^https?:\/\/[^\s'"]+$/.test(cfg.DOKPLOY_URL)) errs.push('DOKPLOY_URL must be an http(s) URL.');
|
|
183
|
+
if (!['off', 'patch', 'minor', 'all'].includes(String(cfg.AUTO_UPGRADE))) errs.push('AUTO_UPGRADE must be off, patch, minor or all.');
|
|
184
|
+
if (!/^\d+$/.test(String(cfg.AUTO_UPGRADE_HOURS)) || Number(cfg.AUTO_UPGRADE_HOURS) < 1) errs.push('AUTO_UPGRADE_HOURS must be a whole number of hours, at least 1.');
|
|
185
|
+
if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
|
|
186
|
+
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
187
|
+
for (const k of ['RES_CPU_CRITICAL', 'RES_MEM_CRITICAL', 'RES_DISK_CRITICAL']) {
|
|
188
|
+
if (!/^\d+$/.test(String(cfg[k])) || Number(cfg[k]) < 1 || Number(cfg[k]) > 100) errs.push(`${k} must be a percentage, 1-100.`);
|
|
189
|
+
}
|
|
173
190
|
for (const k of ['DOKPLOY_TOOL_PRESET', 'DOKPLOY_ENABLED_TAGS', 'DOKPLOY_DISABLED_TAGS']) {
|
|
174
191
|
if (cfg[k] && !/^[A-Za-z0-9_,-]+$/.test(cfg[k])) errs.push(`${k} must be a comma-separated list of names (e.g. project,application,postgres).`);
|
|
175
192
|
}
|
|
@@ -219,6 +236,8 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
|
|
|
219
236
|
HD_PROFILE: p.profile,
|
|
220
237
|
HD_UNITS: units.join(' '),
|
|
221
238
|
HD_PLATFORM: platformId,
|
|
239
|
+
HD_AUTO_UPGRADE: cfg.AUTO_UPGRADE,
|
|
240
|
+
HD_AUTO_UPGRADE_HOURS: cfg.AUTO_UPGRADE_HOURS,
|
|
222
241
|
// Linux: the virtual display. macOS: the real screen, no DISPLAY.
|
|
223
242
|
...(platformId === 'linux' ? { DISPLAY: `:${cfg.DISPLAY_NUM}` } : {}),
|
|
224
243
|
// Services start with a bare PATH; keep the one the installer ran with, so
|
|
@@ -254,8 +273,15 @@ export const SETTABLE_KEYS = {
|
|
|
254
273
|
DOKPLOY_ENABLED_TAGS: 'Dokploy MCP tool categories to load (needs install to apply)',
|
|
255
274
|
DOKPLOY_DISABLED_TAGS: 'Dokploy MCP tool categories to drop (needs install to apply)',
|
|
256
275
|
TRANSCRIPT_DAYS: 'days Claude keeps conversation transcripts, at least 30 (needs install to apply)',
|
|
276
|
+
AUTO_UPGRADE: 'automatic upgrades from npm: off, patch, minor (default) or all (needs install to apply)',
|
|
277
|
+
AUTO_UPGRADE_HOURS: 'hours between automatic upgrade checks (needs install to apply)',
|
|
278
|
+
RESOURCE_GUARD: 'on = new work waits while CPU/RAM/disk is critical, off = no checks (needs install to apply)',
|
|
279
|
+
RES_WAIT_SECONDS: 'how long new work waits for a critical device to recover before it is refused',
|
|
280
|
+
RES_CPU_CRITICAL: 'CPU busy % that counts as critical',
|
|
281
|
+
RES_MEM_CRITICAL: 'available RAM % at or below which the device is critical',
|
|
282
|
+
RES_DISK_CRITICAL: 'free disk % at or below which the device is critical',
|
|
257
283
|
};
|
|
258
|
-
const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS)/;
|
|
284
|
+
const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS|AUTO_UPGRADE|RESOURCE_GUARD)/;
|
|
259
285
|
|
|
260
286
|
/** Validate and save one settable key; returns { key, value, needsInstall }. */
|
|
261
287
|
export function setConfigValue(key, value, env = process.env) {
|
package/src/device.js
CHANGED
|
@@ -8,6 +8,7 @@ import { capture, ok, httpJson, which } from './util.js';
|
|
|
8
8
|
import { listSessions, listProcs, recentEvents } from './state.js';
|
|
9
9
|
import { loadConfig, saveConfig, mergePorts } from './config.js';
|
|
10
10
|
import * as ngrok from './ngrok.js';
|
|
11
|
+
import * as resources from './resources.js';
|
|
11
12
|
|
|
12
13
|
const short = (u) => u.replace(/^harness-/, '');
|
|
13
14
|
const logical = (name) => (name.startsWith('harness-') ? name : `harness-${name}`).replace(/\.(service|timer)$/, '');
|
|
@@ -53,8 +54,7 @@ export async function status(ctx) {
|
|
|
53
54
|
services: serviceStates(ctx),
|
|
54
55
|
browser: cdp ? cdp.Browser : null,
|
|
55
56
|
viewers: viewers(ctx.cfg, ctx.platform),
|
|
56
|
-
|
|
57
|
-
disk: capture('df', ['-h', '/']),
|
|
57
|
+
resources: await resources.sample(ctx, { quick: true }),
|
|
58
58
|
};
|
|
59
59
|
}
|
|
60
60
|
|
|
@@ -62,7 +62,7 @@ export async function status(ctx) {
|
|
|
62
62
|
export function logs(ctx, target, lines = 100) {
|
|
63
63
|
const n = Math.max(1, Math.min(2000, Number(lines) || 100));
|
|
64
64
|
const proj = ctx.projects.find((p) => p.name === target);
|
|
65
|
-
if (proj || target === 'tests' || /^(rc|proc)-[A-Za-z0-9_-]+$/.test(target)) {
|
|
65
|
+
if (proj || target === 'tests' || target === 'upgrade' || /^(rc|proc)-[A-Za-z0-9_-]+$/.test(target)) {
|
|
66
66
|
const file = path.join(ctx.paths.logs, proj ? `rc-${proj.name}.log` : `${target}.log`);
|
|
67
67
|
return fs.existsSync(file) ? capture('tail', ['-n', String(n), file]) : `(no log yet: ${file})`;
|
|
68
68
|
}
|
package/src/install.js
CHANGED
|
@@ -53,14 +53,15 @@ export async function install(ctx, opts = {}) {
|
|
|
53
53
|
|
|
54
54
|
// 3. A persistent copy of this CLI (for the services, the MCP server and the agent) + user-level tools.
|
|
55
55
|
log.step('Installing the harness-device CLI and user-level tools');
|
|
56
|
-
|
|
56
|
+
// --skip-pkg: an upgrade already put this exact version in pkg.
|
|
57
|
+
if (!opts.skipPkg) run('npm', ['install', '--prefix', p.pkg, '--no-fund', '--no-audit', '--omit=dev', installSpec()], { dryRun, env });
|
|
57
58
|
for (const c of ctx.caps) for (const [cmd, args] of c.userInstall ? c.userInstall(ctx) : []) run(cmd, args, { dryRun, env });
|
|
58
59
|
for (const b of ['harness-device', ...ctx.caps.flatMap((c) => c.links || [])]) link(path.join(p.pkg, 'node_modules', '.bin', b), path.join(p.bin, b), dryRun);
|
|
59
60
|
link(path.join(p.bin, 'harness-device'), path.join(env.HOME || os.homedir(), '.local', 'bin', 'harness-device'), dryRun);
|
|
60
61
|
|
|
61
62
|
// 4. Services that start at boot (Linux) / login (macOS) and restart on failure.
|
|
62
63
|
log.step(`Services → ${p.units}`);
|
|
63
|
-
plat.activate(ctx, plat.renderServices(ctx, !dryRun), { dryRun });
|
|
64
|
+
plat.activate(ctx, plat.renderServices(ctx, !dryRun), { dryRun, graceful: !!opts.graceful });
|
|
64
65
|
run(path.join(p.bin, 'hd-heal'), [], { dryRun, env, allowFail: true });
|
|
65
66
|
|
|
66
67
|
// 5. Wire capabilities into the agent.
|
package/src/mcp/server.js
CHANGED
|
@@ -12,12 +12,22 @@ import * as state from '../state.js';
|
|
|
12
12
|
import * as ngrok from '../ngrok.js';
|
|
13
13
|
import { PKG, sendChildOutputToStderr } from '../util.js';
|
|
14
14
|
import { SETTABLE_KEYS, setConfigValue } from '../config.js';
|
|
15
|
+
import * as resources from '../resources.js';
|
|
16
|
+
import * as upgrader from '../upgrade.js';
|
|
15
17
|
|
|
16
18
|
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
17
19
|
const fail = (e) => ({ isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] });
|
|
18
20
|
|
|
19
21
|
const has = (ctx, id) => ctx.caps.some((c) => c.id === id);
|
|
20
22
|
|
|
23
|
+
/** `force`: skip waiting for a critical device (and be refused while it stays critical). */
|
|
24
|
+
const FORCE = { force: z.boolean().optional().describe('skip waiting when the device is critical; refused while critical') };
|
|
25
|
+
|
|
26
|
+
/** Resource guard for new work: waits while CPU/RAM/disk is critical, refuses if it stays so. */
|
|
27
|
+
async function guard(c, a, what) {
|
|
28
|
+
await resources.gate(c, { force: !!a.force, what, waitSeconds: Math.min(Number(c.cfg.RES_WAIT_SECONDS) || 0, 240) });
|
|
29
|
+
}
|
|
30
|
+
|
|
21
31
|
/** Thrown when the user declines or cancels a form; reported as a plain result, not a failure. */
|
|
22
32
|
class Cancelled extends Error {}
|
|
23
33
|
|
|
@@ -50,6 +60,7 @@ export function buildServer(env = process.env) {
|
|
|
50
60
|
try {
|
|
51
61
|
return await fn(ctx(), args || {});
|
|
52
62
|
} catch (e) {
|
|
63
|
+
if (e instanceof resources.ResourceDenied) return fail(`${e.message}\n${resources.summary(e.sample)}`);
|
|
53
64
|
return e instanceof Cancelled ? text(e.message) : fail(e);
|
|
54
65
|
}
|
|
55
66
|
});
|
|
@@ -64,8 +75,9 @@ export function buildServer(env = process.env) {
|
|
|
64
75
|
async (c) => text(state.listProcs(c)));
|
|
65
76
|
|
|
66
77
|
tool('proc_add', 'Register a long-running process so it keeps running across crashes and reboots, in tmux window proc-<name>. Use this instead of running servers in the foreground. Re-adding a name replaces it.',
|
|
67
|
-
{ name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), dir: z.string().optional().describe('absolute working directory (asked if missing)'), command: z.string().optional().describe('one shell line, e.g. "npm run dev -- --port 5173" (asked if missing)') },
|
|
78
|
+
{ name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), dir: z.string().optional().describe('absolute working directory (asked if missing)'), command: z.string().optional().describe('one shell line, e.g. "npm run dev -- --port 5173" (asked if missing)'), ...FORCE },
|
|
68
79
|
async (c, a) => {
|
|
80
|
+
await guard(c, a, `starting process ${a.name}`);
|
|
69
81
|
if (!a.dir || !a.command) {
|
|
70
82
|
const first = c.projects[0];
|
|
71
83
|
const got = await ask(server, `Details for the long-running process "${a.name}"`, {
|
|
@@ -118,14 +130,17 @@ export function buildServer(env = process.env) {
|
|
|
118
130
|
dir: z.string().describe('absolute path of the project (folder with playwright.config)'),
|
|
119
131
|
args: z.array(z.string()).optional().describe('extra playwright test args, e.g. ["tests/login.spec.ts", "--project=chromium"]'),
|
|
120
132
|
timeoutMinutes: z.number().int().min(1).max(120).optional(),
|
|
133
|
+
...FORCE,
|
|
121
134
|
},
|
|
122
135
|
async (c, a) => {
|
|
136
|
+
await guard(c, a, 'a test run');
|
|
123
137
|
if (!path.isAbsolute(a.dir) || !fs.existsSync(a.dir)) throw new Error(`Not an existing absolute path: ${a.dir}`);
|
|
124
138
|
return text(await device.runTestsLive(c, a.dir, a.args || [], (a.timeoutMinutes || 15) * 60000));
|
|
125
139
|
});
|
|
126
140
|
tool('playwright_ui', 'Open (or stop) Playwright UI mode for a project, for the user to watch and re-run tests interactively.',
|
|
127
|
-
{ dir: z.string().optional(), stop: z.boolean().optional() },
|
|
141
|
+
{ dir: z.string().optional(), stop: z.boolean().optional(), ...FORCE },
|
|
128
142
|
async (c, a) => {
|
|
143
|
+
if (!a.stop) await guard(c, a, 'Playwright UI');
|
|
129
144
|
if (!a.stop && (!a.dir || !path.isAbsolute(a.dir) || !fs.existsSync(a.dir))) throw new Error('dir (an existing absolute path) is required unless stop is true');
|
|
130
145
|
return text(device.pwUi(c, a.dir, !!a.stop) + `\nURL: ${device.viewers(c.cfg, c.platform).playwrightUi}`);
|
|
131
146
|
});
|
|
@@ -165,6 +180,19 @@ export function buildServer(env = process.env) {
|
|
|
165
180
|
});
|
|
166
181
|
}
|
|
167
182
|
|
|
183
|
+
tool('resources', 'CPU, RAM and disk (persistent storage) on this device now, with the resource guard\'s level: ok, high or critical. Check it before heavy work (builds, test runs, containers, big installs).', {},
|
|
184
|
+
async (c) => text(await resources.sample(c)));
|
|
185
|
+
|
|
186
|
+
tool('upgrade', 'Check for a newer harness-device on npm, or upgrade to it (the user approves this call). Upgrades run in the background without stopping sessions or unchanged services; the device also does this on its own per AUTO_UPGRADE. check=true only reports.',
|
|
187
|
+
{ check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional() },
|
|
188
|
+
async (c, a) => {
|
|
189
|
+
const chk = await upgrader.check(c, { to: a.version });
|
|
190
|
+
if (a.check || !chk.available || chk.source !== 'npm') return text(chk);
|
|
191
|
+
if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `Upgrade harness-device ${chk.current} → ${chk.latest} now? Sessions keep running; only services whose definitions changed restart.`);
|
|
192
|
+
c.platform.spawnDetached(c, 'upgrade', [path.join(c.paths.bin, 'harness-device'), 'upgrade', '--to', chk.latest], path.join(c.paths.logs, 'upgrade.log'));
|
|
193
|
+
return text(`Upgrading ${chk.current} → ${chk.latest} in the background. Follow it with the logs tool, target "upgrade"; this session gets the new tools when it next restarts.`);
|
|
194
|
+
});
|
|
195
|
+
|
|
168
196
|
tool('config_get', `Current device settings that can be changed with config_set: ${Object.keys(SETTABLE_KEYS).join(', ')}.`, {},
|
|
169
197
|
async (c) => text(Object.fromEntries(Object.keys(SETTABLE_KEYS).map((k) => [k, c.cfg[k] ?? '']))));
|
|
170
198
|
tool('config_set', `Change one device setting (the user approves this call). Never edit files in the device home instead. Keys: ${Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k} (${d})`).join('; ')}. Secrets, capabilities, projects and service ports are changed on the machine, not here.`,
|
package/src/platform/darwin.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import os from 'node:os';
|
|
9
9
|
import path from 'node:path';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
10
11
|
import { PKG_ROOT, run, capture, ok, which, writeFile, color } from '../util.js';
|
|
11
12
|
|
|
12
13
|
export const id = 'darwin';
|
|
@@ -232,3 +233,16 @@ export function viewers(cfg) {
|
|
|
232
233
|
tunnelPorts: [5900, cfg.TTYD_PORT, cfg.PW_UI_PORT],
|
|
233
234
|
};
|
|
234
235
|
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Run a harness-device command in its own process group, so reloading a
|
|
239
|
+
* launchd job (heal included) can't stop it.
|
|
240
|
+
*/
|
|
241
|
+
export function spawnDetached(ctx, name, args, logFile) {
|
|
242
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
243
|
+
const fd = fs.openSync(logFile, 'a');
|
|
244
|
+
const child = spawn(args[0], args.slice(1), { env: ctx.env, detached: true, stdio: ['ignore', fd, fd] });
|
|
245
|
+
child.unref();
|
|
246
|
+
fs.closeSync(fd);
|
|
247
|
+
return child.pid;
|
|
248
|
+
}
|
package/src/platform/linux.js
CHANGED
|
@@ -49,9 +49,12 @@ export function renderServices(ctx, detect = true) {
|
|
|
49
49
|
const sysd = (args, env, opts = {}) => run('systemctl', ['--user', ...args], { env, ...opts });
|
|
50
50
|
|
|
51
51
|
/** Write units, drop stale ones, enable at boot, start; never restart tmux (live sessions). */
|
|
52
|
-
export function activate(ctx, files, { dryRun }) {
|
|
52
|
+
export function activate(ctx, files, { dryRun, graceful = false }) {
|
|
53
53
|
const env = userEnv(ctx.env);
|
|
54
54
|
const dir = serviceDir(env);
|
|
55
|
+
// Graceful (upgrades): restart only services whose unit file changed; the rest
|
|
56
|
+
// pick up new scripts at their next restart.
|
|
57
|
+
const changed = new Set(Object.keys(files).filter((n) => !fs.existsSync(path.join(dir, n)) || fs.readFileSync(path.join(dir, n), 'utf8') !== files[n]));
|
|
55
58
|
const stale = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^harness[.-]/.test(f) && !(f in files)) : [];
|
|
56
59
|
for (const f of stale) {
|
|
57
60
|
sysd(['disable', '--now', f], env, { dryRun, allowFail: true });
|
|
@@ -63,6 +66,9 @@ export function activate(ctx, files, { dryRun }) {
|
|
|
63
66
|
sysd(['enable', 'harness.target', 'harness-heal.timer'], env, { dryRun });
|
|
64
67
|
for (const u of ctx.units) {
|
|
65
68
|
if (u === 'harness-tmux') continue;
|
|
69
|
+
if (graceful && !changed.has(unitName(u))) continue;
|
|
70
|
+
// Never restart heal from inside an upgrade it may be running; the timer starts it next time.
|
|
71
|
+
if (graceful && u === 'harness-heal') continue;
|
|
66
72
|
sysd([u === 'harness-heal' ? 'restart' : 'try-restart', unitName(u)], env, { dryRun, allowFail: true });
|
|
67
73
|
}
|
|
68
74
|
sysd(['start', 'harness.target'], env, { dryRun });
|
|
@@ -140,3 +146,14 @@ export function viewers(cfg) {
|
|
|
140
146
|
tunnelPorts: [cfg.NOVNC_PORT, cfg.TTYD_PORT, cfg.PW_UI_PORT],
|
|
141
147
|
};
|
|
142
148
|
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Run a harness-device command outside every harness service (a transient
|
|
152
|
+
* user unit), so reloading those services, heal included, can't stop it.
|
|
153
|
+
*/
|
|
154
|
+
export function spawnDetached(ctx, name, args, logFile) {
|
|
155
|
+
const env = userEnv(ctx.env);
|
|
156
|
+
const setenv = ['PATH', 'HOME', 'HARNESS_DEVICE_HOME', 'CLAUDE_CONFIG_DIR'].filter((k) => env[k]).map((k) => `--setenv=${k}=${env[k]}`);
|
|
157
|
+
return run('systemd-run', ['--user', '--quiet', '--collect', `--unit=harness-${name}-${Date.now()}`, ...setenv,
|
|
158
|
+
'/bin/sh', '-c', 'exec "$0" "$@" >> "' + logFile.replace(/"/g, '') + '" 2>&1', ...args], { env, allowFail: true });
|
|
159
|
+
}
|
package/src/providers/claude.js
CHANGED
|
@@ -49,6 +49,25 @@ export function removeBlock(text) {
|
|
|
49
49
|
* themselves are never removed or recorded as ours.
|
|
50
50
|
* Returns { settings, added } where added is the new record to keep.
|
|
51
51
|
*/
|
|
52
|
+
const GATE_HOOK = 'hd-gate-hook';
|
|
53
|
+
const isOurHook = (entry) => (entry.hooks || []).some((h) => String(h.command || '').endsWith(GATE_HOOK));
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Put the device's resource guard on Bash (PreToolUse), or take it off.
|
|
57
|
+
* Only an entry whose command is our hd-gate-hook is ever touched.
|
|
58
|
+
*/
|
|
59
|
+
export function mergeGateHook(settings, { bin, on, timeoutSeconds = 360 }) {
|
|
60
|
+
const s = JSON.parse(JSON.stringify(settings || {}));
|
|
61
|
+
const pre = ((s.hooks && s.hooks.PreToolUse) || []).filter((e) => !isOurHook(e));
|
|
62
|
+
if (on) pre.push({ matcher: 'Bash', hooks: [{ type: 'command', command: path.join(bin, GATE_HOOK), timeout: timeoutSeconds }] });
|
|
63
|
+
if (pre.length) s.hooks = { ...(s.hooks || {}), PreToolUse: pre };
|
|
64
|
+
else if (s.hooks) {
|
|
65
|
+
delete s.hooks.PreToolUse;
|
|
66
|
+
if (!Object.keys(s.hooks).length) delete s.hooks;
|
|
67
|
+
}
|
|
68
|
+
return s;
|
|
69
|
+
}
|
|
70
|
+
|
|
52
71
|
export function mergePermissions(settings, { allow = [], deny = [] }, prev = { allow: [], deny: [] }) {
|
|
53
72
|
const s = JSON.parse(JSON.stringify(settings || {}));
|
|
54
73
|
s.permissions = s.permissions || {};
|
|
@@ -147,7 +166,7 @@ export function userMcpServers(env) {
|
|
|
147
166
|
// harness-device MCP tools that only read, or restart the browser. proc_add,
|
|
148
167
|
// proc_remove, restart_service and playwright_ui still ask: they start or stop things.
|
|
149
168
|
export const HARNESS_TOOLS_ALLOWED = ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs',
|
|
150
|
-
'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status', 'config_get'].map((t) => `mcp__harness-device__${t}`);
|
|
169
|
+
'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status', 'config_get', 'resources'].map((t) => `mcp__harness-device__${t}`);
|
|
151
170
|
|
|
152
171
|
/**
|
|
153
172
|
* A Read() rule for an absolute path. In Claude Code rules `/x` is relative to
|
|
@@ -217,7 +236,11 @@ export function apply(ctx) {
|
|
|
217
236
|
pathRule('Edit', path.join(paths.home, '**'), home),
|
|
218
237
|
...DEVICE_ADMIN_DENY,
|
|
219
238
|
]))];
|
|
220
|
-
const
|
|
239
|
+
const merged = mergePermissions(readJson(f.settings, {}), { allow, deny }, prev);
|
|
240
|
+
const added = merged.added;
|
|
241
|
+
// Resource guard on the agent's shell commands (waits while the device is critical).
|
|
242
|
+
const settings = mergeGateHook(merged.settings, { bin: paths.bin, on: String(ctx.cfg.RESOURCE_GUARD || 'on') !== 'off',
|
|
243
|
+
timeoutSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 300, 540) + 60 });
|
|
221
244
|
// Restores resume conversations from their transcripts, so Claude Code
|
|
222
245
|
// must not clean them up early (its default is 30 days).
|
|
223
246
|
const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
|
|
@@ -236,7 +259,7 @@ export function remove(ctx) {
|
|
|
236
259
|
if (fs.existsSync(f.claudeMd)) writeFile(f.claudeMd, removeBlock(fs.readFileSync(f.claudeMd, 'utf8')), { dryRun });
|
|
237
260
|
const stateFile = path.join(paths.home, 'claude-permissions.json');
|
|
238
261
|
const prev = readJson(stateFile, { allow: [], deny: [] });
|
|
239
|
-
if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(unmergePermissions(readJson(f.settings, {}), prev), null, 2) + '\n', { dryRun });
|
|
262
|
+
if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(mergeGateHook(unmergePermissions(readJson(f.settings, {}), prev), { on: false }), null, 2) + '\n', { dryRun });
|
|
240
263
|
if (!dryRun) fs.rmSync(stateFile, { force: true });
|
|
241
264
|
}
|
|
242
265
|
|
package/src/resources.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Resource awareness: CPU, RAM and disk (persistent storage) on this device.
|
|
2
|
+
// New work from a session (registered processes, test runs, heavy shell
|
|
3
|
+
// commands through the provider's hook) passes through gate(): when the device
|
|
4
|
+
// is critical it waits for it to recover; a forced request is refused instead
|
|
5
|
+
// while it stays critical, never run on top of it.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import { capture } from './util.js';
|
|
10
|
+
|
|
11
|
+
const GiB = 1024 ** 3;
|
|
12
|
+
const RANK = { ok: 0, high: 1, critical: 2 };
|
|
13
|
+
const worst = (...ls) => ls.reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'ok');
|
|
14
|
+
const num = (v, d) => (Number.isFinite(Number(v)) && String(v).trim() !== '' ? Number(v) : d);
|
|
15
|
+
|
|
16
|
+
/** Thresholds from config (percent values). */
|
|
17
|
+
export function thresholds(cfg = {}) {
|
|
18
|
+
return {
|
|
19
|
+
cpuCritical: num(cfg.RES_CPU_CRITICAL, 95), // busy % (and at least one runnable task per core)
|
|
20
|
+
cpuHigh: Math.min(num(cfg.RES_CPU_CRITICAL, 95), 85),
|
|
21
|
+
memCritical: num(cfg.RES_MEM_CRITICAL, 5), // % of RAM still available
|
|
22
|
+
memHigh: Math.max(num(cfg.RES_MEM_CRITICAL, 5), 12),
|
|
23
|
+
diskCritical: num(cfg.RES_DISK_CRITICAL, 3), // % free on a device or project filesystem
|
|
24
|
+
diskHigh: Math.max(num(cfg.RES_DISK_CRITICAL, 3), 10),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Busy % of all cores over `ms` (from os.cpus() tick counters). */
|
|
29
|
+
async function cpuBusy(ms) {
|
|
30
|
+
const snap = () => os.cpus().reduce((a, c) => {
|
|
31
|
+
const t = Object.values(c.times).reduce((x, y) => x + y, 0);
|
|
32
|
+
return { idle: a.idle + c.times.idle, total: a.total + t };
|
|
33
|
+
}, { idle: 0, total: 0 });
|
|
34
|
+
const a = snap();
|
|
35
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
36
|
+
const b = snap();
|
|
37
|
+
const total = b.total - a.total;
|
|
38
|
+
return total > 0 ? Math.round(100 * (1 - (b.idle - a.idle) / total)) : 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** RAM: total and available bytes (what can be used without swapping). */
|
|
42
|
+
export function memory(platform = process.platform, read = fs.readFileSync, run = capture) {
|
|
43
|
+
const total = os.totalmem();
|
|
44
|
+
if (platform === 'linux') {
|
|
45
|
+
try {
|
|
46
|
+
const m = Object.fromEntries(read('/proc/meminfo', 'utf8').split('\n').map((l) => l.match(/^(\w+):\s+(\d+)/)).filter(Boolean).map((x) => [x[1], Number(x[2]) * 1024]));
|
|
47
|
+
if (m.MemAvailable !== undefined) return { total: m.MemTotal || total, available: m.MemAvailable };
|
|
48
|
+
} catch { /* fall through */ }
|
|
49
|
+
}
|
|
50
|
+
if (platform === 'darwin') {
|
|
51
|
+
// The kernel's own "memory available" level, the figure Activity Monitor's pressure is based on.
|
|
52
|
+
const level = Number(run('sysctl', ['-n', 'kern.memorystatus_level'], { timeout: 3000 }));
|
|
53
|
+
if (Number.isFinite(level) && level > 0 && level <= 100) return { total, available: Math.round((total * level) / 100) };
|
|
54
|
+
const vm = run('vm_stat', [], { timeout: 3000 });
|
|
55
|
+
const page = Number((vm.match(/page size of (\d+)/) || [])[1] || 4096);
|
|
56
|
+
const pages = (k) => Number((vm.match(new RegExp(`Pages ${k}:\\s+(\\d+)`)) || [])[1] || 0);
|
|
57
|
+
if (vm) return { total, available: (pages('free') + pages('inactive') + pages('speculative') + pages('purgeable')) * page };
|
|
58
|
+
}
|
|
59
|
+
return { total, available: os.freemem() };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Disk: one entry per filesystem holding any of `dirs`. */
|
|
63
|
+
export function disks(dirs, run = capture) {
|
|
64
|
+
const existing = [...new Set(dirs.filter((d) => d && fs.existsSync(d)))];
|
|
65
|
+
if (!existing.length) return [];
|
|
66
|
+
const out = run('df', ['-Pk', ...existing], { timeout: 5000 });
|
|
67
|
+
const seen = new Map();
|
|
68
|
+
out.split('\n').slice(1).forEach((line, i) => {
|
|
69
|
+
const f = line.trim().split(/\s+/);
|
|
70
|
+
if (f.length < 6) return;
|
|
71
|
+
const total = Number(f[1]) * 1024;
|
|
72
|
+
const free = Number(f[3]) * 1024;
|
|
73
|
+
const mount = f.slice(5).join(' ');
|
|
74
|
+
if (!seen.has(mount)) seen.set(mount, { mount, total, free, freePct: total ? Math.round((100 * free) / total) : 100, dirs: [] });
|
|
75
|
+
if (existing[i]) seen.get(mount).dirs.push(existing[i]);
|
|
76
|
+
});
|
|
77
|
+
return [...seen.values()];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* One reading of the device. `quick` skips the CPU sample unless the load
|
|
82
|
+
* average already says the CPUs are saturated (keeps the shell hook fast).
|
|
83
|
+
*/
|
|
84
|
+
export async function sample(ctx, { quick = false, sampleMs = 400 } = {}) {
|
|
85
|
+
const t = thresholds(ctx.cfg);
|
|
86
|
+
const cores = os.cpus().length || 1;
|
|
87
|
+
const load1 = os.loadavg()[0];
|
|
88
|
+
const loadPct = Math.round((100 * load1) / cores);
|
|
89
|
+
const busy = quick && loadPct < 100 ? null : await cpuBusy(sampleMs);
|
|
90
|
+
const cpuLevel = busy !== null && busy >= t.cpuCritical && loadPct >= 100 ? 'critical'
|
|
91
|
+
: (busy ?? loadPct) >= t.cpuHigh ? 'high' : 'ok';
|
|
92
|
+
|
|
93
|
+
const m = memory();
|
|
94
|
+
const memPct = m.total ? Math.round((100 * m.available) / m.total) : 100;
|
|
95
|
+
const memLevel = memPct <= t.memCritical ? 'critical' : memPct <= t.memHigh ? 'high' : 'ok';
|
|
96
|
+
|
|
97
|
+
const d = disks([ctx.paths.home, ...(ctx.projects || []).map((p) => p.dir)]);
|
|
98
|
+
for (const x of d) {
|
|
99
|
+
x.level = x.freePct <= t.diskCritical || x.free < 1 * GiB ? 'critical' : x.freePct <= t.diskHigh || x.free < 5 * GiB ? 'high' : 'ok';
|
|
100
|
+
}
|
|
101
|
+
const diskLevel = worst(...d.map((x) => x.level));
|
|
102
|
+
|
|
103
|
+
const level = worst(cpuLevel, memLevel, diskLevel);
|
|
104
|
+
const reasons = [];
|
|
105
|
+
if (cpuLevel !== 'ok') reasons.push(`CPU ${busy ?? loadPct}% busy (load ${load1.toFixed(2)} on ${cores} cores)`);
|
|
106
|
+
if (memLevel !== 'ok') reasons.push(`RAM ${memPct}% available (${(m.available / GiB).toFixed(1)} of ${(m.total / GiB).toFixed(1)} GiB)`);
|
|
107
|
+
for (const x of d) if (x.level !== 'ok') reasons.push(`disk ${x.mount} ${x.freePct}% free (${(x.free / GiB).toFixed(1)} GiB)`);
|
|
108
|
+
return {
|
|
109
|
+
level,
|
|
110
|
+
reasons,
|
|
111
|
+
cpu: { level: cpuLevel, busyPct: busy, loadPct, load1: Number(load1.toFixed(2)), cores },
|
|
112
|
+
memory: { level: memLevel, availablePct: memPct, availableGiB: Number((m.available / GiB).toFixed(2)), totalGiB: Number((m.total / GiB).toFixed(2)) },
|
|
113
|
+
disk: { level: diskLevel, filesystems: d.map((x) => ({ mount: x.mount, level: x.level, freePct: x.freePct, freeGiB: Number((x.free / GiB).toFixed(1)), dirs: x.dirs })) },
|
|
114
|
+
thresholds: t,
|
|
115
|
+
at: new Date().toISOString(),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function summary(s) {
|
|
120
|
+
const disk = s.disk.filesystems.map((x) => `${x.mount} ${x.freePct}% free`).join(', ') || 'n/a';
|
|
121
|
+
return `${s.level.toUpperCase()} · CPU ${s.cpu.busyPct ?? s.cpu.loadPct}% (load ${s.cpu.load1}/${s.cpu.cores}) · RAM ${s.memory.availablePct}% available · disk ${disk}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export class ResourceDenied extends Error {
|
|
125
|
+
constructor(msg, s) { super(msg); this.sample = s; }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Let new work start only when the device can take it.
|
|
130
|
+
* ok / high → go (high is reported).
|
|
131
|
+
* critical → wait up to waitSeconds for it to recover, then refuse;
|
|
132
|
+
* critical + force → refused at once (forcing never overrides a critical device).
|
|
133
|
+
* RESOURCE_GUARD=off turns the gate off.
|
|
134
|
+
*/
|
|
135
|
+
export async function gate(ctx, { force = false, waitSeconds, what = 'this', quick = false, poll = 5, onWait } = {}) {
|
|
136
|
+
if (String(ctx.cfg.RESOURCE_GUARD || 'on') === 'off') return { allowed: true, level: 'unchecked', waited: 0 };
|
|
137
|
+
const wait = waitSeconds ?? num(ctx.cfg.RES_WAIT_SECONDS, 300);
|
|
138
|
+
let s = await sample(ctx, { quick });
|
|
139
|
+
if (s.level !== 'critical') return { allowed: true, level: s.level, waited: 0, reasons: s.reasons };
|
|
140
|
+
if (force) {
|
|
141
|
+
throw new ResourceDenied(`Refused ${what}: the device is critical (${s.reasons.join('; ')}). Forcing is not allowed while it is critical; free resources first (stop a process, prune Docker, clear disk) or let it wait.`, s);
|
|
142
|
+
}
|
|
143
|
+
const start = Date.now();
|
|
144
|
+
while ((Date.now() - start) / 1000 < wait) {
|
|
145
|
+
if (onWait) onWait(s, Math.round((Date.now() - start) / 1000));
|
|
146
|
+
await new Promise((r) => setTimeout(r, poll * 1000));
|
|
147
|
+
s = await sample(ctx, { quick });
|
|
148
|
+
if (s.level !== 'critical') return { allowed: true, level: s.level, waited: Math.round((Date.now() - start) / 1000), reasons: s.reasons };
|
|
149
|
+
}
|
|
150
|
+
throw new ResourceDenied(`Waited ${wait}s for the device to recover before ${what}, but it is still critical (${s.reasons.join('; ')}). Try again later, or free resources first.`, s);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Shell commands that only look or free resources never wait (checking and
|
|
154
|
+
// fixing a critical device must stay possible).
|
|
155
|
+
const LIGHT = [
|
|
156
|
+
/^(ps|top|htop|free|df|du|uptime|vm_stat|sysctl|iostat|vmstat|nproc|kill|pkill|killall|ls|pwd|cat|head|tail|less|wc|grep|rg|find|echo|printf|which|type|stat|date|env|id|whoami|rm|true)\b/,
|
|
157
|
+
/^git (status|log|diff|show|branch|remote|stash list)\b/,
|
|
158
|
+
/^harness-device (status|logs|events|resources|gate|doctor|proc (list|rm)|session list|ngrok (status|down)|config get|tunnel)\b/,
|
|
159
|
+
/^docker (ps|stop|kill|rm|rmi|logs|stats|system (df|prune)|image (ls|prune)|container (ls|prune)|volume (ls|prune)|builder prune)\b/,
|
|
160
|
+
/^tmux (ls|list-\w+|kill-window|display-message|capture-pane|has-session)\b/,
|
|
161
|
+
/^(npm|pnpm|yarn) cache (clean|verify)\b/,
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
/** True when every part of a shell command line is light. */
|
|
165
|
+
export function isLightCommand(cmd) {
|
|
166
|
+
const parts = String(cmd || '').split(/&&|\|\||;|\||\n/).map((x) => x.trim().replace(/^(\w+=\S*\s+)+/, '').replace(/^(sudo|command|exec|time|nice(\s+-n\s*\d+)?)\s+/, '')).filter(Boolean);
|
|
167
|
+
return parts.length > 0 && parts.every((p) => LIGHT.some((re) => re.test(p)));
|
|
168
|
+
}
|
package/src/upgrade.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Upgrades without downtime. A new version is installed next to the running
|
|
2
|
+
// one (pkg.next), checked, swapped in with renames, and then applied by the
|
|
3
|
+
// NEW version's own install in graceful mode: scripts replaced atomically,
|
|
4
|
+
// only services whose definitions changed are restarted, and the tmux
|
|
5
|
+
// service, which holds every agent session, is never restarted. If anything
|
|
6
|
+
// fails, the previous version is swapped back and re-applied.
|
|
7
|
+
//
|
|
8
|
+
// Automatic upgrades: hd-heal calls `upgrade --auto --detach` every
|
|
9
|
+
// AUTO_UPGRADE_HOURS; AUTO_UPGRADE limits how far it goes (patch, minor, all,
|
|
10
|
+
// off). The work runs detached from the heal job (which an upgrade may reload).
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
import { PKG, capture } from './util.js';
|
|
16
|
+
import { event } from './state.js';
|
|
17
|
+
import { sample } from './resources.js';
|
|
18
|
+
|
|
19
|
+
export const POLICIES = ['off', 'patch', 'minor', 'all'];
|
|
20
|
+
|
|
21
|
+
const parse = (v) => String(v).replace(/^v/, '').split('-')[0].split('.').map((x) => Number(x) || 0);
|
|
22
|
+
|
|
23
|
+
/** -1, 0 or 1. Pre-release versions never count as newer. */
|
|
24
|
+
export function compare(a, b) {
|
|
25
|
+
const p = parse(a);
|
|
26
|
+
const q = parse(b);
|
|
27
|
+
for (let i = 0; i < 3; i++) if (p[i] !== q[i]) return p[i] < q[i] ? -1 : 1;
|
|
28
|
+
return 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Is moving from `from` to `to` within the policy? */
|
|
32
|
+
export function allowedBy(policy, from, to) {
|
|
33
|
+
if (compare(to, from) <= 0 || String(to).includes('-')) return false;
|
|
34
|
+
const [a, b] = [parse(from), parse(to)];
|
|
35
|
+
if (policy === 'all') return true;
|
|
36
|
+
if (policy === 'minor') return a[0] === b[0];
|
|
37
|
+
if (policy === 'patch') return a[0] === b[0] && a[1] === b[1];
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const pkgDir = (root) => path.join(root, 'node_modules', ...PKG.name.split('/'));
|
|
42
|
+
|
|
43
|
+
/** Where the services' copy lives and whether it came from npm or a source folder. */
|
|
44
|
+
export function installed(ctx) {
|
|
45
|
+
const dir = pkgDir(ctx.paths.pkg);
|
|
46
|
+
if (!fs.existsSync(dir)) return { version: null, source: 'none' };
|
|
47
|
+
const source = fs.lstatSync(dir).isSymbolicLink() ? 'folder' : 'npm';
|
|
48
|
+
let version = null;
|
|
49
|
+
try { version = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version; } catch { /* broken */ }
|
|
50
|
+
return { version, source, dir };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function latest(ctx, tag = 'latest') {
|
|
54
|
+
const v = capture('npm', ['view', `${PKG.name}@${tag}`, 'version'], { env: ctx.env, timeout: 30000 }).trim();
|
|
55
|
+
return /^\d+\.\d+\.\d+/.test(v) ? v : null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function check(ctx, { to } = {}) {
|
|
59
|
+
const inst = installed(ctx);
|
|
60
|
+
const policy = POLICIES.includes(String(ctx.cfg.AUTO_UPGRADE)) ? String(ctx.cfg.AUTO_UPGRADE) : 'minor';
|
|
61
|
+
const target = to || latest(ctx);
|
|
62
|
+
const current = inst.version || PKG.version;
|
|
63
|
+
const out = { current, latest: target, policy, source: inst.source, available: !!target && compare(target, current) > 0 };
|
|
64
|
+
out.autoAllowed = out.available && inst.source === 'npm' && allowedBy(policy, current, target);
|
|
65
|
+
if (!target) out.note = 'could not reach the npm registry';
|
|
66
|
+
else if (inst.source === 'folder') out.note = 'installed from a source folder: upgrade by updating that folder and running install';
|
|
67
|
+
else if (out.available && !out.autoAllowed) out.note = `newer version, outside AUTO_UPGRADE=${policy}: upgrade it yourself (harness-device upgrade)`;
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function lock(ctx) {
|
|
72
|
+
const f = path.join(ctx.paths.state, 'upgrade.lock');
|
|
73
|
+
fs.mkdirSync(ctx.paths.state, { recursive: true });
|
|
74
|
+
try {
|
|
75
|
+
fs.writeFileSync(f, String(process.pid), { flag: 'wx' });
|
|
76
|
+
} catch {
|
|
77
|
+
const pid = Number(fs.readFileSync(f, 'utf8'));
|
|
78
|
+
let alive = false;
|
|
79
|
+
try { process.kill(pid, 0); alive = true; } catch { /* gone */ }
|
|
80
|
+
if (alive) throw new Error(`An upgrade is already running (pid ${pid}).`);
|
|
81
|
+
fs.writeFileSync(f, String(process.pid));
|
|
82
|
+
}
|
|
83
|
+
return () => fs.rmSync(f, { force: true });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const npmRun = (ctx, args) => spawnSync('npm', args, { env: ctx.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15 * 60000 });
|
|
87
|
+
|
|
88
|
+
/** Apply a version already in pkg: its own install, graceful, no system packages. */
|
|
89
|
+
function applyInstalled(ctx, log) {
|
|
90
|
+
const cli = path.join(pkgDir(ctx.paths.pkg), 'bin', 'harness-device.js');
|
|
91
|
+
const r = spawnSync(process.execPath, [cli, 'install', '--skip-system', '--skip-pkg', '--graceful'], { env: ctx.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 15 * 60000 });
|
|
92
|
+
log((r.stdout || '') + (r.stderr || ''));
|
|
93
|
+
return r.status === 0;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Install `to` next to the running copy, swap it in, apply it gracefully.
|
|
98
|
+
* Rolls back to the previous copy if installing or applying fails.
|
|
99
|
+
*/
|
|
100
|
+
export async function upgrade(ctx, { to, auto = false, log = () => {} } = {}) {
|
|
101
|
+
const c = await check(ctx, { to });
|
|
102
|
+
if (!c.latest) throw new Error('Could not reach the npm registry.');
|
|
103
|
+
if (c.source === 'folder') throw new Error('This device runs harness-device from a source folder; update the folder and run install instead.');
|
|
104
|
+
if (!c.available) return { upgraded: false, ...c, note: `already on ${c.current}` };
|
|
105
|
+
if (auto && !c.autoAllowed) return { upgraded: false, ...c };
|
|
106
|
+
|
|
107
|
+
// Never upgrade on top of a busy device: the next check tries again.
|
|
108
|
+
const s = await sample(ctx);
|
|
109
|
+
if (s.level === 'critical' || (auto && s.level === 'high')) {
|
|
110
|
+
event(ctx, `upgrade to ${c.latest} deferred: device ${s.level} (${s.reasons.join('; ')})`);
|
|
111
|
+
return { upgraded: false, deferred: true, ...c, note: `deferred, device ${s.level}: ${s.reasons.join('; ')}` };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const unlock = lock(ctx);
|
|
115
|
+
const p = ctx.paths;
|
|
116
|
+
const next = `${p.pkg}.next`;
|
|
117
|
+
const prev = `${p.pkg}.prev`;
|
|
118
|
+
try {
|
|
119
|
+
log(`upgrade ${c.current} → ${c.latest}: installing next to the running copy`);
|
|
120
|
+
fs.rmSync(next, { recursive: true, force: true });
|
|
121
|
+
fs.mkdirSync(next, { recursive: true });
|
|
122
|
+
const r = npmRun(ctx, ['install', '--prefix', next, '--no-fund', '--no-audit', '--omit=dev', `${PKG.name}@${c.latest}`]);
|
|
123
|
+
if (r.status !== 0) throw new Error(`npm install failed: ${(r.stderr || '').trim().split('\n').slice(-3).join(' ')}`);
|
|
124
|
+
const got = JSON.parse(fs.readFileSync(path.join(pkgDir(next), 'package.json'), 'utf8')).version;
|
|
125
|
+
if (got !== c.latest) throw new Error(`installed ${got}, expected ${c.latest}`);
|
|
126
|
+
const v = spawnSync(process.execPath, [path.join(pkgDir(next), 'bin', 'harness-device.js'), '--version'], { encoding: 'utf8', env: ctx.env });
|
|
127
|
+
if (v.status !== 0 || v.stdout.trim() !== c.latest) throw new Error('the new version does not start');
|
|
128
|
+
|
|
129
|
+
// Swap: the bin/ links point at pkg/node_modules/.bin, so they follow.
|
|
130
|
+
fs.rmSync(prev, { recursive: true, force: true });
|
|
131
|
+
fs.renameSync(p.pkg, prev);
|
|
132
|
+
fs.renameSync(next, p.pkg);
|
|
133
|
+
log('swapped in; applying (graceful: running sessions and unchanged services are left alone)');
|
|
134
|
+
if (!applyInstalled(ctx, log)) {
|
|
135
|
+
log('applying the new version failed; rolling back');
|
|
136
|
+
fs.renameSync(p.pkg, `${p.pkg}.failed-${c.latest}`);
|
|
137
|
+
fs.renameSync(prev, p.pkg);
|
|
138
|
+
applyInstalled(ctx, log);
|
|
139
|
+
event(ctx, `upgrade to ${c.latest} failed and was rolled back to ${c.current}`);
|
|
140
|
+
throw new Error(`Upgrade to ${c.latest} failed; rolled back to ${c.current}. See logs/upgrade.log.`);
|
|
141
|
+
}
|
|
142
|
+
event(ctx, `upgraded harness-device ${c.current} → ${c.latest}${auto ? ' (automatic)' : ''}`);
|
|
143
|
+
return { upgraded: true, from: c.current, to: c.latest, note: 'sessions keep running; each picks up the new device tools when it next restarts' };
|
|
144
|
+
} catch (e) {
|
|
145
|
+
fs.rmSync(next, { recursive: true, force: true });
|
|
146
|
+
if (!/rolled back/.test(e.message)) event(ctx, `upgrade to ${c.latest} failed: ${e.message}`);
|
|
147
|
+
throw e;
|
|
148
|
+
} finally {
|
|
149
|
+
unlock();
|
|
150
|
+
}
|
|
151
|
+
}
|