@dreamtree-org/harness-device 0.1.3 → 0.1.5
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 +12 -0
- package/README.md +30 -1
- package/package.json +1 -1
- package/sh/bin/hd-gate-hook +6 -0
- package/sh/bin/hd-heal +25 -0
- package/sh/bin/hd-proc-loop +2 -1
- package/sh/bin/hd-rc-loop +3 -0
- package/src/capabilities.js +10 -0
- package/src/cli.js +120 -5
- package/src/config.js +27 -1
- package/src/device.js +5 -3
- package/src/install.js +3 -2
- package/src/lifecycle.js +139 -0
- package/src/mcp/server.js +42 -3
- package/src/platform/darwin.js +46 -0
- package/src/platform/linux.js +39 -1
- package/src/providers/claude.js +29 -4
- package/src/resources.js +168 -0
- package/src/upgrade.js +151 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.5
|
|
4
|
+
|
|
5
|
+
- **`harness-device stop | start | restart`, graceful, on macOS and Linux.** Stop holds the heal job, closes public URLs, waits for every agent session to finish its turn (`--timeout`, default 120 s; `--now` skips), ends sessions with `/exit` and registered processes with Ctrl-C, closes the browser over CDP so its tabs come back, then stops the services. It stays stopped, also across reboots and logins (`launchctl disable` / `systemctl --user disable`), until `start`. `restart` is a stop followed by a start; every session resumes its pinned conversation, and the device starts again even if stopping fails.
|
|
6
|
+
- **`device_restart` MCP tool:** a session can ask for a graceful restart (you approve it; it runs detached and resumes the session afterwards). `stop`/`start` stay at the machine: they are denied to sessions.
|
|
7
|
+
- `status` shows when the device was stopped on purpose; the heal job leaves a stopped device alone.
|
|
8
|
+
|
|
9
|
+
## 0.1.4
|
|
10
|
+
|
|
11
|
+
- **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.
|
|
12
|
+
- **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`.
|
|
13
|
+
- **Graceful activation on Linux:** `install --graceful` restarts only services whose unit changed (macOS already did).
|
|
14
|
+
|
|
3
15
|
## 0.1.3
|
|
4
16
|
|
|
5
17
|
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
|
@@ -125,9 +125,38 @@ harness-device doctor # "Dokploy API accepts the key"
|
|
|
125
125
|
|
|
126
126
|
Secrets in Dokploy's API responses (env vars, passwords, tokens) are redacted before they reach the agent (`DOKPLOY_REDACT_ENV=true`). To load fewer Dokploy tools, add any of these to `config.env` and run `install` again: `DOKPLOY_TOOL_PRESET`, `DOKPLOY_ENABLED_TAGS=project,application,postgres`, `DOKPLOY_DISABLED_TAGS`. If you already have your own `dokploy` MCP server, install leaves it as it is and the device's is not registered.
|
|
127
127
|
|
|
128
|
+
### Stop, start, restart
|
|
129
|
+
|
|
130
|
+
Run these on the machine (a terminal or SSH), not from a session: stopping ends every session.
|
|
131
|
+
|
|
132
|
+
```bash
|
|
133
|
+
harness-device stop # graceful: waits for agent turns to finish (up to --timeout 120 s), ends
|
|
134
|
+
# sessions with /exit and processes with Ctrl-C, saves the browser's tabs;
|
|
135
|
+
# stays stopped, also after a reboot or login, until start
|
|
136
|
+
harness-device start # everything comes back; each session resumes its pinned conversation
|
|
137
|
+
harness-device restart # graceful stop, then start
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`--now` ends sessions without waiting for their turn. A session can ask for a restart with the `device_restart` tool (you approve it); it ends with the others and resumes its conversation about a minute later. `harness-device restart <service>` still restarts one service.
|
|
141
|
+
|
|
128
142
|
### Updating
|
|
129
143
|
|
|
130
|
-
|
|
144
|
+
**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:
|
|
145
|
+
- scripts are replaced atomically
|
|
146
|
+
- only services whose definitions changed are restarted
|
|
147
|
+
- the tmux service, which holds every agent session, is never restarted
|
|
148
|
+
|
|
149
|
+
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`.
|
|
150
|
+
|
|
151
|
+
**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`.
|
|
152
|
+
|
|
153
|
+
### Resource guard
|
|
154
|
+
|
|
155
|
+
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).
|
|
156
|
+
- Commands that only look or free resources always run: `ps`, `df`, `kill`, `docker stop`/`prune`, `rm`, `harness-device status`/`resources`/`proc rm`.
|
|
157
|
+
- Forcing (`force`, `--force`, `HD_FORCE=1`) skips the wait, and is refused outright while the device is critical.
|
|
158
|
+
- 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`.
|
|
159
|
+
- The heal job records every move into or out of critical in `events`.
|
|
131
160
|
|
|
132
161
|
## Commands
|
|
133
162
|
|
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.5",
|
|
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
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
# macOS). Restarts dead or hung services, rebuilds tmux windows from state.
|
|
4
4
|
set -uo pipefail
|
|
5
5
|
. "$(dirname "$0")/hd-lib.sh"
|
|
6
|
+
# Stopped or mid-restart on purpose (harness-device stop|restart): leave everything alone.
|
|
7
|
+
if [ -e "$HD_STATE/stopped" ] || [ -e "$HD_STATE/restarting" ]; then exit 0; fi
|
|
6
8
|
# HD_UNITS (runtime.env) lists the services the enabled capabilities own.
|
|
7
9
|
# tmux is handled below (its session is the thing to check); heal is us.
|
|
8
10
|
for u in ${HD_UNITS:-}; do
|
|
@@ -31,3 +33,26 @@ else
|
|
|
31
33
|
hd_log "tmux session $HD_SESSION is gone; restarting harness-tmux"
|
|
32
34
|
hd_svc_restart harness-tmux || true
|
|
33
35
|
fi
|
|
36
|
+
# Resources: record when the device crosses into or out of critical (the
|
|
37
|
+
# guard makes new work wait meanwhile; this leaves a trail for `events`).
|
|
38
|
+
lvl=$("$HD_HOME/bin/harness-device" resources --json 2>/dev/null | sed -n 's/^ "level": "\([a-z]*\)".*/\1/p' | head -1)
|
|
39
|
+
prev=$(cat "$HD_STATE/resource-level" 2>/dev/null || echo ok)
|
|
40
|
+
if [ -n "$lvl" ] && [ "$lvl" != "$prev" ]; then
|
|
41
|
+
mkdir -p "$HD_STATE"; echo "$lvl" > "$HD_STATE/resource-level"
|
|
42
|
+
if [ "$lvl" = critical ] || [ "$prev" = critical ]; then
|
|
43
|
+
hd_event "resources $prev → $lvl: $("$HD_HOME/bin/harness-device" resources 2>/dev/null | head -1)"
|
|
44
|
+
fi
|
|
45
|
+
fi
|
|
46
|
+
# Automatic upgrades from npm, at most every AUTO_UPGRADE_HOURS. The check runs
|
|
47
|
+
# here; the upgrade itself runs detached (it may reload this very job).
|
|
48
|
+
if [ "${HD_AUTO_UPGRADE:-off}" != off ]; then
|
|
49
|
+
due=$(cat "$HD_STATE/upgrade-due" 2>/dev/null || echo 0)
|
|
50
|
+
now=$(date +%s)
|
|
51
|
+
case "$due" in ''|*[!0-9]*) due=0 ;; esac
|
|
52
|
+
if [ "$now" -ge "$due" ]; then
|
|
53
|
+
mkdir -p "$HD_STATE"
|
|
54
|
+
echo $(( now + ${HD_AUTO_UPGRADE_HOURS:-6} * 3600 )) > "$HD_STATE/upgrade-due"
|
|
55
|
+
mkdir -p "$HD_HOME/logs"
|
|
56
|
+
"$HD_HOME/bin/harness-device" upgrade --auto --detach >> "$HD_HOME/logs/upgrade.log" 2>&1 || hd_log "upgrade check failed (logs/upgrade.log)"
|
|
57
|
+
fi
|
|
58
|
+
fi
|
package/sh/bin/hd-proc-loop
CHANGED
|
@@ -8,13 +8,14 @@ name="$1"
|
|
|
8
8
|
f="$HD_STATE/procs/$name"
|
|
9
9
|
hd_strip_anthropic
|
|
10
10
|
delay=2
|
|
11
|
-
while [ -f "$f.cmd" ]; do
|
|
11
|
+
while [ -f "$f.cmd" ] && [ ! -e "$HD_STATE/stopping" ]; do
|
|
12
12
|
cd "$(cat "$f.dir" 2>/dev/null || echo "$HOME")" || exit 1
|
|
13
13
|
started=$(date +%s)
|
|
14
14
|
hd_log "proc $name: $(cat "$f.cmd")"
|
|
15
15
|
bash -c "$(cat "$f.cmd")"
|
|
16
16
|
code=$?
|
|
17
17
|
[ -f "$f.cmd" ] || break
|
|
18
|
+
[ -e "$HD_STATE/stopping" ] && { hd_log "proc $name ended (device stopping)"; exit 0; }
|
|
18
19
|
ran=$(( $(date +%s) - started ))
|
|
19
20
|
if [ "$ran" -ge 120 ]; then delay=2; else delay=$(( delay * 2 )); [ "$delay" -gt 120 ] && delay=120; fi
|
|
20
21
|
hd_log "proc $name exited with $code after ${ran}s; restarting in ${delay}s"
|
package/sh/bin/hd-rc-loop
CHANGED
|
@@ -12,6 +12,8 @@ slotf="$HD_STATE/sessions/$name/$slot"
|
|
|
12
12
|
|
|
13
13
|
delay=2; fast=0
|
|
14
14
|
while true; do
|
|
15
|
+
# harness-device stop/restart ends sessions on purpose: don't serve again.
|
|
16
|
+
[ -e "$HD_STATE/stopping" ] && { hd_log "device is stopping; $name/$slot not restarted"; exit 0; }
|
|
15
17
|
[ "$slot" = - ] || [ -f "$slotf" ] || { hd_log "slot $name/$slot was removed; stopping"; exit 0; }
|
|
16
18
|
started=$(date +%s)
|
|
17
19
|
if [ "$slot" = - ]; then
|
|
@@ -23,6 +25,7 @@ while true; do
|
|
|
23
25
|
"$(dirname "$0")/hd-serve-${HD_PROVIDER:-claude}" "$label" "$id"
|
|
24
26
|
fi
|
|
25
27
|
code=$?
|
|
28
|
+
[ -e "$HD_STATE/stopping" ] && { hd_log "device is stopping; $name/$slot ended (code $code)"; exit 0; }
|
|
26
29
|
ran=$(( $(date +%s) - started ))
|
|
27
30
|
if [ "$ran" -ge 300 ]; then delay=2; fast=0; else delay=$(( delay * 2 )); fast=$(( fast + 1 )); [ "$delay" -gt 300 ] && delay=300; fi
|
|
28
31
|
# Never swap the conversation automatically: a fast failure is usually a
|
package/src/capabilities.js
CHANGED
|
@@ -83,6 +83,16 @@ 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.
|
|
95
|
+
- To restart the whole device (after an upgrade, or when things are wedged), call \`device_restart\`; tell the user first that this session ends and resumes in about a minute. Stopping the device (\`harness-device stop\`/\`start\`) is done at the machine.
|
|
86
96
|
- 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
97
|
},
|
|
88
98
|
|
package/src/cli.js
CHANGED
|
@@ -12,6 +12,9 @@ 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 lifecycle from './lifecycle.js';
|
|
16
|
+
import * as resources from './resources.js';
|
|
17
|
+
import * as upgrader from './upgrade.js';
|
|
15
18
|
import { PKG, log, color, run, writeFile, capture } from './util.js';
|
|
16
19
|
|
|
17
20
|
const HELP = `${color.bold('harness-device')} ${PKG.version}: a reboot-proof dev device for remote AI agents (Claude Remote Control first)
|
|
@@ -43,6 +46,13 @@ ${color.bold('Device')}
|
|
|
43
46
|
config get [KEY] | set KEY=VALUE settings a remote session may change (ngrok, Dokploy filters, transcript days)
|
|
44
47
|
ngrok token | up [viewers|apps|all|<tunnel>]... [--port 8099] | down | status
|
|
45
48
|
restart <service> restart one harness service (chromium, ttyd, ...)
|
|
49
|
+
resources [--json] CPU, RAM and disk now, with the guard's level (ok, high, critical)
|
|
50
|
+
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
51
|
+
stop [--now] [--timeout 120] graceful shutdown: waits for agent turns to finish, ends sessions and processes
|
|
52
|
+
cleanly, saves the browser; stays stopped (also after reboots) until start
|
|
53
|
+
start start everything; every session resumes its conversation
|
|
54
|
+
restart [--now] [--timeout 120] graceful stop, then start (restart <service> restarts one service)
|
|
55
|
+
upgrade [--check] [--to x.y.z] upgrade from npm without stopping sessions (AUTO_UPGRADE does it on its own)
|
|
46
56
|
mcp run the harness-device MCP server (stdio)
|
|
47
57
|
|
|
48
58
|
${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
@@ -53,8 +63,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
53
63
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
54
64
|
`;
|
|
55
65
|
|
|
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'];
|
|
66
|
+
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now'];
|
|
67
|
+
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
58
68
|
|
|
59
69
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
60
70
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -124,6 +134,12 @@ function setSecret(file, key, value) {
|
|
|
124
134
|
|
|
125
135
|
function printStatus(s) {
|
|
126
136
|
console.log(`${color.bold(s.device)} ${color.dim(`· ${s.provider} · ${s.serveMode} mode · ${s.capabilities.join(', ')}`)}`);
|
|
137
|
+
if (s.stopped) console.log(color.yellow(`stopped on purpose since ${s.stopped.since} (${s.stopped.why}); start it with: harness-device start`));
|
|
138
|
+
if (s.resources) {
|
|
139
|
+
const r = s.resources;
|
|
140
|
+
const paint = r.level === 'critical' ? color.red : r.level === 'high' ? color.yellow : color.green;
|
|
141
|
+
console.log(`${paint(resources.summary(r))}${r.reasons.length ? color.dim(`\n ${r.reasons.join('\n ')}`) : ''}`);
|
|
142
|
+
}
|
|
127
143
|
console.log(color.bold('\nsessions'));
|
|
128
144
|
if (!s.sessions.length) console.log(color.dim(' none (harness-device project add name:/dir)'));
|
|
129
145
|
for (const x of s.sessions) {
|
|
@@ -139,7 +155,6 @@ function printStatus(s) {
|
|
|
139
155
|
console.log(' ' + s.services.map((x) => `${x.state === 'active' ? color.green('●') : color.red('○')} ${x.unit.replace(/^harness-/, '')}`).join(' '));
|
|
140
156
|
console.log(color.bold('\nviewers') + color.dim(' (127.0.0.1; harness-device tunnel)'));
|
|
141
157
|
console.log(` display ${s.viewers.display}\n tmux ${s.viewers.tmux}`);
|
|
142
|
-
console.log(`\n${color.dim(s.load)}`);
|
|
143
158
|
if (s.browser) console.log(color.dim(`browser: ${s.browser}`));
|
|
144
159
|
}
|
|
145
160
|
|
|
@@ -181,7 +196,54 @@ export async function main(argv) {
|
|
|
181
196
|
|
|
182
197
|
case 'install': {
|
|
183
198
|
const ctx = loadContext(env, { dryRun: !!f.dryRun });
|
|
184
|
-
return install(ctx, { skipSystem: !!f.skipSystem });
|
|
199
|
+
return install(ctx, { skipSystem: !!f.skipSystem, skipPkg: !!f.skipPkg, graceful: !!f.graceful });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
case 'upgrade': {
|
|
203
|
+
const ctx = loadContext(env);
|
|
204
|
+
const to = f.to && String(f.to);
|
|
205
|
+
if (to && !/^\d+\.\d+\.\d+$/.test(to)) throw new Error('--to takes a version such as 0.2.0');
|
|
206
|
+
if (f.check) {
|
|
207
|
+
const c = await upgrader.check(ctx, { to });
|
|
208
|
+
if (f.json) return console.log(JSON.stringify(c, null, 2));
|
|
209
|
+
console.log(`installed ${c.current} (${c.source}) · latest ${c.latest || '?'} · AUTO_UPGRADE=${c.policy}${c.available ? color.bold(' → update available') : ''}`);
|
|
210
|
+
if (c.note) console.log(color.dim(` ${c.note}`));
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
if (f.detach) {
|
|
214
|
+
// From heal (or the MCP tool): check here, do the work outside every harness service.
|
|
215
|
+
const c = await upgrader.check(ctx, { to });
|
|
216
|
+
const go = f.auto ? c.autoAllowed : c.available && c.source === 'npm';
|
|
217
|
+
if (!go) return console.log(`no upgrade: ${c.note || `on ${c.current}, latest ${c.latest}`}`);
|
|
218
|
+
const bin = path.join(ctx.paths.bin, 'harness-device');
|
|
219
|
+
ctx.platform.spawnDetached(ctx, 'upgrade', [bin, 'upgrade', ...(f.auto ? ['--auto'] : []), '--to', c.latest], path.join(ctx.paths.logs, 'upgrade.log'));
|
|
220
|
+
return console.log(`upgrading ${c.current} → ${c.latest} in the background (harness-device logs upgrade)`);
|
|
221
|
+
}
|
|
222
|
+
const r = await upgrader.upgrade(ctx, { to, auto: !!f.auto, log: (m) => console.log(`[${new Date().toISOString()}] ${m}`.trimEnd()) });
|
|
223
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
224
|
+
return r.upgraded ? log.ok(`Upgraded ${r.from} → ${r.to}. ${r.note}`) : console.log(`no upgrade: ${r.note || `on ${r.current}, latest ${r.latest}`}`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
case 'resources': {
|
|
228
|
+
const ctx = loadContext(env);
|
|
229
|
+
const s = await resources.sample(ctx);
|
|
230
|
+
return f.json ? console.log(JSON.stringify(s, null, 2)) : console.log(resources.summary(s) + (s.reasons.length ? `\n ${s.reasons.join('\n ')}` : ''));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
case 'gate': {
|
|
234
|
+
const ctx = loadContext(env);
|
|
235
|
+
if (f.hook) return gateHook(ctx);
|
|
236
|
+
try {
|
|
237
|
+
const r = await resources.gate(ctx, { force: !!f.force, waitSeconds: f.wait !== undefined ? Number(f.wait) : undefined, what: 'this command',
|
|
238
|
+
onWait: (s, t) => process.stderr.write(`device critical (${s.reasons.join('; ')}); waiting ${t}s…\n`) });
|
|
239
|
+
if (r.level === 'high') log.warn(`device busy: ${r.reasons.join('; ')}`);
|
|
240
|
+
return;
|
|
241
|
+
} catch (e) {
|
|
242
|
+
if (!(e instanceof resources.ResourceDenied)) throw e;
|
|
243
|
+
console.error(e.message);
|
|
244
|
+
process.exitCode = 3;
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
185
247
|
}
|
|
186
248
|
|
|
187
249
|
case 'uninstall':
|
|
@@ -231,6 +293,7 @@ export async function main(argv) {
|
|
|
231
293
|
return;
|
|
232
294
|
}
|
|
233
295
|
if (sub === 'new') {
|
|
296
|
+
await resources.gate(ctx, { force: !!f.force, what: 'a new session' });
|
|
234
297
|
const r = state.newSlot(ctx, rest[0]);
|
|
235
298
|
log.ok(`${rest[0]} slot ${r.slot}: conversation ${r.id} (window ${state.windowName(rest[0], r.slot)})`);
|
|
236
299
|
return state.applyLayout(ctx);
|
|
@@ -256,6 +319,7 @@ export async function main(argv) {
|
|
|
256
319
|
const [name, dir, ...cmdParts] = rest;
|
|
257
320
|
if (!cmdParts.length) throw new Error("usage: proc add <name> <dir> '<command>'");
|
|
258
321
|
guardOwn(ctx, `proc-${name}`, f);
|
|
322
|
+
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
323
|
state.addProc(ctx, name, path.resolve(dir), cmdParts.join(' '));
|
|
260
324
|
return log.ok(`proc ${name} registered; running in tmux window proc-${name}`);
|
|
261
325
|
}
|
|
@@ -368,8 +432,37 @@ export async function main(argv) {
|
|
|
368
432
|
return;
|
|
369
433
|
}
|
|
370
434
|
|
|
435
|
+
case 'stop':
|
|
436
|
+
case 'start': {
|
|
437
|
+
const ctx = loadContext(env);
|
|
438
|
+
const say = (m) => console.log(color.dim(` ${m}`));
|
|
439
|
+
if (cmd === 'start') {
|
|
440
|
+
await lifecycle.startDevice(ctx, { log: say });
|
|
441
|
+
return log.ok('Started. harness-device status shows the sessions as they come back.');
|
|
442
|
+
}
|
|
443
|
+
if (process.env.TMUX_PANE && ownWindow() && !f.force) throw new Error('This shell runs inside the harness tmux session, which stop ends. Run it from a plain terminal or SSH shell, or add --force.');
|
|
444
|
+
const timeoutMs = f.timeout ? Math.max(0, Number(f.timeout)) * 1000 : 120000;
|
|
445
|
+
if (!Number.isFinite(timeoutMs)) throw new Error('--timeout takes seconds');
|
|
446
|
+
await lifecycle.stopDevice(ctx, { now: !!f.now, timeoutMs, log: say });
|
|
447
|
+
return log.ok('Stopped. It stays stopped, also after a reboot, until: harness-device start');
|
|
448
|
+
}
|
|
449
|
+
|
|
371
450
|
case 'restart': {
|
|
372
|
-
if (!sub)
|
|
451
|
+
if (!sub) {
|
|
452
|
+
const ctx = loadContext(env);
|
|
453
|
+
const say = (m) => console.log(color.dim(` ${m}`));
|
|
454
|
+
const timeoutMs = f.timeout ? Math.max(0, Number(f.timeout)) * 1000 : 120000;
|
|
455
|
+
if (!Number.isFinite(timeoutMs)) throw new Error('--timeout takes seconds');
|
|
456
|
+
if (process.env.TMUX_PANE && ownWindow() && !f.detach && !f.force) throw new Error('This shell runs inside the harness tmux session, which a restart ends. Run it from a plain terminal, add --detach (runs in the background), or --force.');
|
|
457
|
+
if (f.detach) {
|
|
458
|
+
const bin = path.join(ctx.paths.bin, 'harness-device');
|
|
459
|
+
const own = ownWindow();
|
|
460
|
+
ctx.platform.spawnDetached(ctx, 'restart', [bin, 'restart', ...(f.now ? ['--now'] : []), '--timeout', String(timeoutMs / 1000), ...(own ? ['--except', own] : []), '--force'], path.join(ctx.paths.logs, 'restart.log'));
|
|
461
|
+
return console.log('restarting in the background (harness-device logs restart); sessions resume their conversations');
|
|
462
|
+
}
|
|
463
|
+
await lifecycle.restartDevice(ctx, { now: !!f.now, timeoutMs, except: f.except ? [String(f.except)] : [], log: say });
|
|
464
|
+
return log.ok('Restarted. Sessions are resuming their conversations (harness-device status).');
|
|
465
|
+
}
|
|
373
466
|
const ctx = loadContext(env);
|
|
374
467
|
const tmux = device.isTmux(sub);
|
|
375
468
|
if (tmux && process.env.TMUX_PANE && !f.force) throw new Error('This shell runs inside the harness tmux session: restarting tmux would end it, and every Remote Control session. Run it from a plain SSH shell, or add --force.');
|
|
@@ -400,3 +493,25 @@ export async function main(argv) {
|
|
|
400
493
|
throw new Error(`Unknown command "${cmd}". Run: harness-device help`);
|
|
401
494
|
}
|
|
402
495
|
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Claude Code PreToolUse hook (Bash): commands that only look or free
|
|
499
|
+
* resources pass at once; anything else waits while the device is critical and
|
|
500
|
+
* is refused if it stays critical (or if HD_FORCE=1 asks to skip the wait).
|
|
501
|
+
* Any error lets the command through: the guard must never wedge a session.
|
|
502
|
+
*/
|
|
503
|
+
async function gateHook(ctx) {
|
|
504
|
+
try {
|
|
505
|
+
const input = JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
|
|
506
|
+
const cmd = (input.tool_input && input.tool_input.command) || '';
|
|
507
|
+
if (resources.isLightCommand(cmd)) return;
|
|
508
|
+
const force = /(^|\s)HD_FORCE=1(\s|$)/.test(cmd);
|
|
509
|
+
try {
|
|
510
|
+
await resources.gate(ctx, { force, quick: true, waitSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 0, 540), what: 'this command' });
|
|
511
|
+
} catch (e) {
|
|
512
|
+
if (!(e instanceof resources.ResourceDenied)) return;
|
|
513
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
514
|
+
permissionDecisionReason: `${e.message} Check with: harness-device resources.` } }));
|
|
515
|
+
}
|
|
516
|
+
} catch { /* fail open */ }
|
|
517
|
+
}
|
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,8 @@ 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 { isStopped } from './lifecycle.js';
|
|
12
|
+
import * as resources from './resources.js';
|
|
11
13
|
|
|
12
14
|
const short = (u) => u.replace(/^harness-/, '');
|
|
13
15
|
const logical = (name) => (name.startsWith('harness-') ? name : `harness-${name}`).replace(/\.(service|timer)$/, '');
|
|
@@ -47,14 +49,14 @@ export async function status(ctx) {
|
|
|
47
49
|
provider: ctx.cfg.PROVIDER,
|
|
48
50
|
capabilities: ctx.caps.map((c) => c.id),
|
|
49
51
|
serveMode: ctx.cfg.SERVE_MODE,
|
|
52
|
+
stopped: isStopped(ctx),
|
|
50
53
|
sessions: listSessions(ctx),
|
|
51
54
|
procs: listProcs(ctx),
|
|
52
55
|
events: recentEvents(ctx, 10),
|
|
53
56
|
services: serviceStates(ctx),
|
|
54
57
|
browser: cdp ? cdp.Browser : null,
|
|
55
58
|
viewers: viewers(ctx.cfg, ctx.platform),
|
|
56
|
-
|
|
57
|
-
disk: capture('df', ['-h', '/']),
|
|
59
|
+
resources: await resources.sample(ctx, { quick: true }),
|
|
58
60
|
};
|
|
59
61
|
}
|
|
60
62
|
|
|
@@ -62,7 +64,7 @@ export async function status(ctx) {
|
|
|
62
64
|
export function logs(ctx, target, lines = 100) {
|
|
63
65
|
const n = Math.max(1, Math.min(2000, Number(lines) || 100));
|
|
64
66
|
const proj = ctx.projects.find((p) => p.name === target);
|
|
65
|
-
if (proj ||
|
|
67
|
+
if (proj || ['tests', 'upgrade', 'restart'].includes(target) || /^(rc|proc)-[A-Za-z0-9_-]+$/.test(target)) {
|
|
66
68
|
const file = path.join(ctx.paths.logs, proj ? `rc-${proj.name}.log` : `${target}.log`);
|
|
67
69
|
return fs.existsSync(file) ? capture('tail', ['-n', String(n), file]) : `(no log yet: ${file})`;
|
|
68
70
|
}
|
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/lifecycle.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Graceful stop, start and restart of the whole device, on both platforms.
|
|
2
|
+
//
|
|
3
|
+
// Stop: hold the heal job (it would restart what we stop), close public URLs,
|
|
4
|
+
// wait for every agent session to finish its turn, end sessions and processes
|
|
5
|
+
// the way a user would (/exit, Ctrl-C), close the browser over CDP so its tabs
|
|
6
|
+
// are saved, then stop the services. `stop` keeps the device stopped (also
|
|
7
|
+
// across reboots) until `start`; `restart` starts it again right away, and
|
|
8
|
+
// every session resumes its pinned conversation.
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { capture, ok, httpJson } from './util.js';
|
|
13
|
+
import { listSessions, listProcs, event } from './state.js';
|
|
14
|
+
|
|
15
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
|
+
const flag = (ctx, name) => path.join(ctx.paths.state, name);
|
|
17
|
+
const tmux = (ctx, args) => ok('tmux', args, { env: ctx.env });
|
|
18
|
+
const target = (ctx, win) => `=${ctx.cfg.SESSION}:${win}`;
|
|
19
|
+
/** Claude Code shows this while a turn is running. */
|
|
20
|
+
const BUSY = /esc to interrupt/i;
|
|
21
|
+
|
|
22
|
+
function setFlag(ctx, name, why) {
|
|
23
|
+
fs.mkdirSync(ctx.paths.state, { recursive: true });
|
|
24
|
+
fs.writeFileSync(flag(ctx, name), `${new Date().toISOString()} ${why}\n`);
|
|
25
|
+
}
|
|
26
|
+
const clearFlag = (ctx, name) => fs.rmSync(flag(ctx, name), { force: true });
|
|
27
|
+
|
|
28
|
+
/** { since, why } when the device was stopped on purpose, else null. */
|
|
29
|
+
export function isStopped(ctx) {
|
|
30
|
+
const f = flag(ctx, 'stopped');
|
|
31
|
+
if (!fs.existsSync(f)) return null;
|
|
32
|
+
const [since, ...why] = fs.readFileSync(f, 'utf8').trim().split(' ');
|
|
33
|
+
return { since, why: why.join(' ') };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A session is busy while its transcript changed in the last `quietMs` or its pane shows a running turn. */
|
|
37
|
+
export function sessionBusy(ctx, s, { quietMs = 10000, now = Date.now() } = {}) {
|
|
38
|
+
if (!s.running) return false;
|
|
39
|
+
if (s.transcript && fs.existsSync(s.transcript) && now - fs.statSync(s.transcript).mtimeMs < quietMs) return true;
|
|
40
|
+
const pane = capture('tmux', ['capture-pane', '-p', '-t', target(ctx, s.window)], { env: ctx.env });
|
|
41
|
+
return BUSY.test(pane || '');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Wait until no session is busy, or the timeout. Returns the windows still busy. */
|
|
45
|
+
async function waitIdle(ctx, { timeoutMs, log, except = [] }) {
|
|
46
|
+
const end = Date.now() + timeoutMs;
|
|
47
|
+
let busy = [];
|
|
48
|
+
for (;;) {
|
|
49
|
+
busy = listSessions(ctx).filter((s) => !except.includes(s.window) && sessionBusy(ctx, s));
|
|
50
|
+
if (!busy.length || Date.now() >= end) return busy.map((s) => s.window);
|
|
51
|
+
log(`waiting for ${busy.map((s) => s.window).join(', ')} to finish (${Math.ceil((end - Date.now()) / 1000)}s left)`);
|
|
52
|
+
await sleep(Math.min(5000, Math.max(250, end - Date.now())));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const windowAlive = (ctx, win) => (capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}'], { env: ctx.env }) || '').split('\n').includes(win);
|
|
57
|
+
|
|
58
|
+
/** Send keys, wait for the window to close, escalate to Ctrl-C, then kill it. */
|
|
59
|
+
async function endWindow(ctx, win, first, { waitMs }) {
|
|
60
|
+
if (!windowAlive(ctx, win)) return 'gone';
|
|
61
|
+
for (const keys of first) tmux(ctx, ['send-keys', '-t', target(ctx, win), ...keys]);
|
|
62
|
+
for (const [keys, ms] of [[null, waitMs], [['C-c'], 3000], [['C-c'], 3000]]) {
|
|
63
|
+
if (keys) tmux(ctx, ['send-keys', '-t', target(ctx, win), ...keys]);
|
|
64
|
+
for (const end = Date.now() + ms; Date.now() < end; await sleep(250)) if (!windowAlive(ctx, win)) return 'exited';
|
|
65
|
+
}
|
|
66
|
+
tmux(ctx, ['kill-window', '-t', target(ctx, win)]);
|
|
67
|
+
return 'killed';
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Ask Chromium to close itself, so it saves its session (tabs come back). */
|
|
71
|
+
async function closeBrowser(ctx) {
|
|
72
|
+
if (!ctx.caps.some((c) => c.id === 'browser')) return 'off';
|
|
73
|
+
const v = await httpJson(`http://127.0.0.1:${ctx.cfg.CDP_PORT}/json/version`, 2000);
|
|
74
|
+
if (!v || !v.webSocketDebuggerUrl || typeof WebSocket === 'undefined') return 'not running';
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
const ws = new WebSocket(v.webSocketDebuggerUrl);
|
|
77
|
+
const done = (r) => { clearTimeout(t); try { ws.close(); } catch {} resolve(r); };
|
|
78
|
+
const t = setTimeout(() => done('timeout'), 5000);
|
|
79
|
+
ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: 'Browser.close' }));
|
|
80
|
+
ws.onmessage = () => done('closed');
|
|
81
|
+
ws.onclose = () => done('closed');
|
|
82
|
+
ws.onerror = () => done('error');
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Stop the device gracefully.
|
|
88
|
+
* persist: stay stopped (also after a reboot) until start. restart uses false.
|
|
89
|
+
* now: don't wait for sessions to finish their turn.
|
|
90
|
+
* except: windows not to wait for (the session that asked for a restart).
|
|
91
|
+
*/
|
|
92
|
+
export async function stopDevice(ctx, { persist = true, now = false, timeoutMs = 120000, except = [], log = () => {}, why = 'stop' } = {}) {
|
|
93
|
+
setFlag(ctx, persist ? 'stopped' : 'restarting', why);
|
|
94
|
+
log(persist ? 'stopping the device (it stays stopped until: harness-device start)' : 'restarting the device');
|
|
95
|
+
if (ctx.caps.some((c) => c.id === 'ngrok')) { ctx.platform.ngrokDown(ctx); log('public URLs closed'); }
|
|
96
|
+
|
|
97
|
+
if (!now) {
|
|
98
|
+
const busy = await waitIdle(ctx, { timeoutMs, log, except });
|
|
99
|
+
if (busy.length) log(`still busy after ${Math.round(timeoutMs / 1000)}s, ending anyway: ${busy.join(', ')}`);
|
|
100
|
+
}
|
|
101
|
+
setFlag(ctx, 'stopping', why);
|
|
102
|
+
const sessions = listSessions(ctx).filter((s) => s.running);
|
|
103
|
+
const procs = listProcs(ctx).filter((p) => p.running);
|
|
104
|
+
const ended = await Promise.all([
|
|
105
|
+
...sessions.map(async (s) => `${s.window} ${await endWindow(ctx, s.window, [['Escape'], ['C-u'], ['/exit', 'Enter']], { waitMs: 15000 })}`),
|
|
106
|
+
...procs.map(async (p) => `proc-${p.name} ${await endWindow(ctx, `proc-${p.name}`, [['C-c']], { waitMs: 10000 })}`),
|
|
107
|
+
]);
|
|
108
|
+
if (ended.length) log(`ended: ${ended.join(', ')}`);
|
|
109
|
+
const b = await closeBrowser(ctx);
|
|
110
|
+
if (b !== 'off') log(`browser: ${b}`);
|
|
111
|
+
ctx.platform.stopServices(ctx, { persist });
|
|
112
|
+
clearFlag(ctx, 'stopping');
|
|
113
|
+
event(ctx, persist ? `device stopped (${why})` : `device stopping for a restart (${why})`);
|
|
114
|
+
log('services stopped');
|
|
115
|
+
return { stopped: true, persist, ended, browser: b };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Start everything again; every session resumes its pinned conversation. */
|
|
119
|
+
export async function startDevice(ctx, { log = () => {}, why = 'start' } = {}) {
|
|
120
|
+
clearFlag(ctx, 'stopping');
|
|
121
|
+
clearFlag(ctx, 'stopped');
|
|
122
|
+
ctx.platform.startServices(ctx);
|
|
123
|
+
clearFlag(ctx, 'restarting');
|
|
124
|
+
event(ctx, `device started (${why})`);
|
|
125
|
+
log('services started; sessions resume their conversations');
|
|
126
|
+
return { started: true };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Graceful stop (not persisted), then start. */
|
|
130
|
+
export async function restartDevice(ctx, opts = {}) {
|
|
131
|
+
const why = opts.why || 'restart';
|
|
132
|
+
try {
|
|
133
|
+
await stopDevice(ctx, { ...opts, persist: false, why });
|
|
134
|
+
} finally {
|
|
135
|
+
// Whatever happened while stopping, never leave the device down after a restart.
|
|
136
|
+
await startDevice(ctx, { log: opts.log, why });
|
|
137
|
+
}
|
|
138
|
+
return { restarted: true };
|
|
139
|
+
}
|
package/src/mcp/server.js
CHANGED
|
@@ -10,14 +10,24 @@ import { loadContext } from '../context.js';
|
|
|
10
10
|
import * as device from '../device.js';
|
|
11
11
|
import * as state from '../state.js';
|
|
12
12
|
import * as ngrok from '../ngrok.js';
|
|
13
|
-
import { PKG, sendChildOutputToStderr } from '../util.js';
|
|
13
|
+
import { PKG, sendChildOutputToStderr, capture } 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,30 @@ 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
|
+
|
|
196
|
+
tool('device_restart', 'Gracefully restart the whole device (the user approves this call): waits for other sessions to finish their turn, ends sessions and processes cleanly, saves the browser, restarts every service. This session ends too and resumes the same conversation about a minute later; tell the user before calling. Stopping the device is done at the machine (harness-device stop), not from a session.',
|
|
197
|
+
{ now: z.boolean().optional().describe("don't wait for other sessions to finish their turn") },
|
|
198
|
+
async (c, a) => {
|
|
199
|
+
if (server.server.getClientCapabilities()?.elicitation) await confirm(server, 'Restart the whole device now? Every session (this one too) ends and resumes its conversation in about a minute; public URLs close.');
|
|
200
|
+
// The calling session's own turn is still open: don't wait for it.
|
|
201
|
+
const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
|
|
202
|
+
const bin = path.join(c.paths.bin, 'harness-device');
|
|
203
|
+
c.platform.spawnDetached(c, 'restart', [bin, 'restart', '--force', ...(a.now ? ['--now'] : []), ...(own ? ['--except', own] : [])], path.join(c.paths.logs, 'restart.log'));
|
|
204
|
+
return text('Restarting in the background (log: logs tool, target "restart"). This session ends shortly and resumes the same conversation; public URLs stay closed until reopened.');
|
|
205
|
+
});
|
|
206
|
+
|
|
168
207
|
tool('config_get', `Current device settings that can be changed with config_set: ${Object.keys(SETTABLE_KEYS).join(', ')}.`, {},
|
|
169
208
|
async (c) => text(Object.fromEntries(Object.keys(SETTABLE_KEYS).map((k) => [k, c.cfg[k] ?? '']))));
|
|
170
209
|
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,48 @@ 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
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Stop order: heal first (it would restart the rest), tmux last. */
|
|
251
|
+
const STOP_ORDER = (units) => ['harness-heal', ...units.filter((u) => !['harness-heal', 'harness-tmux'].includes(u)), 'harness-tmux'].filter((u) => units.includes(u));
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Unload every harness job. persist: also `launchctl disable`, so they don't
|
|
255
|
+
* load at the next login until startServices. The plists stay in place.
|
|
256
|
+
*/
|
|
257
|
+
export function stopServices(ctx, { persist = false, dryRun = false } = {}) {
|
|
258
|
+
const list = [...STOP_ORDER(ctx.units), 'harness-ngrok'];
|
|
259
|
+
for (const u of list) {
|
|
260
|
+
const l = labelOf(u);
|
|
261
|
+
if (persist) lc(['disable', `${domain()}/${l}`], { dryRun });
|
|
262
|
+
if (!dryRun && !loaded(l)) continue;
|
|
263
|
+
lc(['bootout', `${domain()}/${l}`], { dryRun });
|
|
264
|
+
for (let i = 0; !dryRun && i < 20 && loaded(l); i++) sleepMs(250);
|
|
265
|
+
}
|
|
266
|
+
// The tmux server outlives its supervisor job by design; end it explicitly.
|
|
267
|
+
run('tmux', ['kill-session', '-t', `=${ctx.cfg.SESSION}`], { dryRun, allowFail: true, env: ctx.env });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Enable and load every harness job again (tmux first, heal last). */
|
|
271
|
+
export function startServices(ctx, { dryRun = false } = {}) {
|
|
272
|
+
const dir = serviceDir(ctx.env);
|
|
273
|
+
for (const u of [...STOP_ORDER(ctx.units)].reverse()) {
|
|
274
|
+
const l = labelOf(u);
|
|
275
|
+
lc(['enable', `${domain()}/${l}`], { dryRun });
|
|
276
|
+
const file = path.join(dir, plistName(u));
|
|
277
|
+
if (!dryRun && !fs.existsSync(file)) { console.log(color.yellow(` ! ${file} is missing: run harness-device install`)); continue; }
|
|
278
|
+
if (dryRun || !loaded(l)) bootstrap(file, l, { dryRun });
|
|
279
|
+
}
|
|
280
|
+
}
|
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,35 @@ 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
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Stop every harness service (heal timer first, tmux last). persist: also
|
|
163
|
+
* disable them, so they stay stopped after a reboot until startServices.
|
|
164
|
+
*/
|
|
165
|
+
export function stopServices(ctx, { persist = false, dryRun = false } = {}) {
|
|
166
|
+
const env = userEnv(ctx.env);
|
|
167
|
+
const units = ctx.units.filter((u) => u !== 'harness-heal' && u !== 'harness-tmux');
|
|
168
|
+
sysd(['stop', 'harness-heal.timer', 'harness-heal.service'], env, { dryRun, allowFail: true });
|
|
169
|
+
sysd(['stop', 'harness-ngrok.service'], env, { dryRun, allowFail: true });
|
|
170
|
+
if (units.length) sysd(['stop', ...units.map(unitName)], env, { dryRun, allowFail: true });
|
|
171
|
+
sysd(['stop', 'harness-tmux.service', 'harness.target'], env, { dryRun, allowFail: true });
|
|
172
|
+
if (persist) sysd(['disable', 'harness.target', 'harness-heal.timer'], env, { dryRun, allowFail: true });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Enable and start everything again. */
|
|
176
|
+
export function startServices(ctx, { dryRun = false } = {}) {
|
|
177
|
+
const env = userEnv(ctx.env);
|
|
178
|
+
sysd(['enable', 'harness.target', 'harness-heal.timer'], env, { dryRun });
|
|
179
|
+
sysd(['start', 'harness.target', 'harness-heal.timer'], env, { dryRun });
|
|
180
|
+
}
|
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
|
|
@@ -169,7 +188,9 @@ export function pathRule(tool, abs, home) {
|
|
|
169
188
|
* ngrok_up, proc_add, ...), never by hand.
|
|
170
189
|
*/
|
|
171
190
|
export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-device install:*)',
|
|
172
|
-
'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)'
|
|
191
|
+
'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)',
|
|
192
|
+
// Stopping ends every session and none could start the device again; restart goes through device_restart.
|
|
193
|
+
'Bash(harness-device stop:*)', 'Bash(harness-device start:*)', 'Bash(harness-device restart)', 'Bash(harness-device restart --:*)'];
|
|
173
194
|
|
|
174
195
|
/**
|
|
175
196
|
* Wire everything into Claude Code. ctx: { cfg, caps, projects, paths, env, dryRun, mcpServers }
|
|
@@ -217,7 +238,11 @@ export function apply(ctx) {
|
|
|
217
238
|
pathRule('Edit', path.join(paths.home, '**'), home),
|
|
218
239
|
...DEVICE_ADMIN_DENY,
|
|
219
240
|
]))];
|
|
220
|
-
const
|
|
241
|
+
const merged = mergePermissions(readJson(f.settings, {}), { allow, deny }, prev);
|
|
242
|
+
const added = merged.added;
|
|
243
|
+
// Resource guard on the agent's shell commands (waits while the device is critical).
|
|
244
|
+
const settings = mergeGateHook(merged.settings, { bin: paths.bin, on: String(ctx.cfg.RESOURCE_GUARD || 'on') !== 'off',
|
|
245
|
+
timeoutSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 300, 540) + 60 });
|
|
221
246
|
// Restores resume conversations from their transcripts, so Claude Code
|
|
222
247
|
// must not clean them up early (its default is 30 days).
|
|
223
248
|
const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
|
|
@@ -236,7 +261,7 @@ export function remove(ctx) {
|
|
|
236
261
|
if (fs.existsSync(f.claudeMd)) writeFile(f.claudeMd, removeBlock(fs.readFileSync(f.claudeMd, 'utf8')), { dryRun });
|
|
237
262
|
const stateFile = path.join(paths.home, 'claude-permissions.json');
|
|
238
263
|
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 });
|
|
264
|
+
if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(mergeGateHook(unmergePermissions(readJson(f.settings, {}), prev), { on: false }), null, 2) + '\n', { dryRun });
|
|
240
265
|
if (!dryRun) fs.rmSync(stateFile, { force: true });
|
|
241
266
|
}
|
|
242
267
|
|
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
|
+
}
|