@dreamtree-org/harness-device 0.1.2 → 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 +18 -0
- package/README.md +26 -6
- package/package.json +1 -1
- package/sh/bin/hd-gate-hook +6 -0
- package/sh/bin/hd-heal +23 -0
- package/src/capabilities.js +20 -3
- package/src/cli.js +115 -27
- package/src/config.js +68 -0
- package/src/device.js +45 -3
- package/src/install.js +3 -2
- package/src/mcp/server.js +111 -5
- package/src/platform/darwin.js +14 -0
- package/src/platform/linux.js +18 -1
- package/src/providers/claude.js +61 -5
- package/src/resources.js +168 -0
- package/src/upgrade.js +151 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
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
|
+
|
|
9
|
+
## 0.1.3
|
|
10
|
+
|
|
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.
|
|
12
|
+
|
|
13
|
+
- **New MCP tools** (each asks your approval in the session): `ngrok_up` (groups, single tunnels or app ports; returns the URL and the login), `ngrok_down`, `config_set`. Read-only `config_get` is pre-approved.
|
|
14
|
+
- **`harness-device config get|set`** for the settings a session may change: `NGROK_APP_PORTS`, `NGROK_APPS_PUBLIC`, `NGROK_DOMAIN`, the Dokploy tool filters, `TRANSCRIPT_DAYS`. Secrets, capabilities, projects and service ports stay with `init`/`install`/`secrets` on the machine.
|
|
15
|
+
- **`ngrok up --port 8099`** adds an app port and opens just that tunnel.
|
|
16
|
+
- **Denied in sessions:** editing anything under `~/.harness-device`, and `harness-device init`/`install`/`uninstall`/`secrets`.
|
|
17
|
+
- **Interactive questions:** the skill tells the agent to ask with the provider's interactive prompt (Claude: `AskUserQuestion`, tappable options) instead of questions in prose, never to ask for secrets, and to restate URLs and logins in its reply. Each provider declares this in `interaction` (`askTool`, `supportsElicitation`, `guidance`).
|
|
18
|
+
- **Forms from the device's tools (MCP elicitation):** `ngrok_up`, `config_set` and `proc_add` ask for what's missing in a form (`ngrok_up` lists this device's tunnels); `ngrok_down` and `proc_remove` ask to confirm. Declining changes nothing. Clients without forms get an error naming the missing fields.
|
|
19
|
+
- **Skill:** use the device's tools instead of editing its files, keep test files in the project folder, and never ask the user to run commands on the machine.
|
|
20
|
+
|
|
3
21
|
## 0.1.2
|
|
4
22
|
|
|
5
23
|
- **Dokploy:** secret fields in API responses are redacted before they reach the agent; optional `DOKPLOY_TOOL_PRESET` / `DOKPLOY_ENABLED_TAGS` / `DOKPLOY_DISABLED_TAGS` in config.env limit the tools loaded.
|
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
|
|
|
@@ -146,7 +161,8 @@ Run `install` again with the new version: `npx @dreamtree-org/harness-device@lat
|
|
|
146
161
|
| `restart <service>` | Restart one harness service |
|
|
147
162
|
| `tunnel` | The SSH command for the viewers |
|
|
148
163
|
| `secrets set KEY`, `secrets list`, `secrets rm KEY` | API keys for MCP servers, stored mode 600. Only the MCP servers get them, not the agent's environment |
|
|
149
|
-
| `ngrok token`, `ngrok up viewers\|apps\|all`, `ngrok down`, `ngrok status` | Public URLs, off until you turn them on |
|
|
164
|
+
| `ngrok token`, `ngrok up [viewers\|apps\|all\|<tunnel>] [--port 8099]`, `ngrok down`, `ngrok status` | Public URLs, off until you turn them on |
|
|
165
|
+
| `config get [KEY]`, `config set KEY=VALUE` | The settings a remote session may change (app ports, Dokploy tool filters, transcript days) |
|
|
150
166
|
| `mcp` | The harness-device MCP server (stdio) |
|
|
151
167
|
| `fleet add <name> <user@host>`, `fleet status`, `fleet run <name> <args>` | Many devices from one machine, over ssh |
|
|
152
168
|
| `uninstall [--purge]` | Remove services and agent wiring (`--purge` also deletes state and config) |
|
|
@@ -176,9 +192,13 @@ Extra MCP servers for the agent: add `MCP_<name>=command args` lines to `config.
|
|
|
176
192
|
Remote sessions run commands without anyone at the keyboard, so `install` merges a curated list into `~/.claude/settings.json`. It only ever adds or removes its own entries.
|
|
177
193
|
|
|
178
194
|
- **Pre-approved:** git, npm/npx/node, tmux, curl, docker, sqlite3, graphify, `hd-pw-live`, read-only system commands, the read-only `harness-device` subcommands (`status`, `logs`, `proc list`, `session list`/`new`…), the Playwright and graphify MCP tools, and the harness-device MCP tools that only read (status, sessions, logs, viewers, screenshot…) or restart the browser.
|
|
179
|
-
- **Denied:** `sudo`, `su`, shutdown/reboot, `mkfs`, `dd`, `rm -rf` of `/` or home, `tmux kill-server`/`kill-session`,
|
|
195
|
+
- **Denied:** `sudo`, `su`, shutdown/reboot, `mkfs`, `dd`, `rm -rf` of `/` or home, `tmux kill-server`/`kill-session`, reading `secrets.env`, the ngrok config and `~/.ssh`, **editing anything in `~/.harness-device`**, and `harness-device init`/`install`/`uninstall`/`secrets`.
|
|
180
196
|
- **Never from inside a session:** restarting tmux (it holds every live session); the MCP tool refuses it, and the CLI asks for `--force`.
|
|
181
|
-
- **Everything else asks you**, including Dokploy deploys, registering or removing processes (`
|
|
197
|
+
- **Everything else asks you**, including Dokploy deploys, registering or removing processes (`proc_add`/`proc_remove`), opening public URLs (`ngrok_up`/`ngrok_down`), changing settings (`config_set`) and `session reset`.
|
|
198
|
+
|
|
199
|
+
**Remote first.** You approve those prompts in the session itself, on your phone or claude.ai, so nothing a session does needs you at the machine. A session changes the device only through these tools, never by editing its files, and never asks you to type commands on the machine. Only three things need the machine (locally or over SSH): entering secrets, `init`/`install` (capabilities, projects, upgrades) and the first `claude` login.
|
|
200
|
+
|
|
201
|
+
**Interactive questions.** When the agent needs a decision it asks with the provider's interactive prompt (in Claude, `AskUserQuestion`: tappable options plus "Other"), not a question in prose. The device's own tools show forms for missing details and confirmations (MCP elicitation: pick a tunnel, enter a port, confirm closing URLs). Neither ever asks for a secret.
|
|
182
202
|
|
|
183
203
|
This is a guard against accidents, not a sandbox. Pre-approving `node`, `npx` and `npm` already lets the agent run any code as your user, so give a device only the projects and credentials you would give the agent anyway.
|
|
184
204
|
|
|
@@ -203,7 +223,7 @@ harness-device fleet status # every device: sessions, failing slots, serv
|
|
|
203
223
|
|
|
204
224
|
## Security
|
|
205
225
|
|
|
206
|
-
- Nothing listens publicly. CDP, noVNC, ttyd and Playwright UI bind to 127.0.0.1, and Remote Control is outbound HTTPS only. ngrok tunnels open only when you run `ngrok up
|
|
226
|
+
- Nothing listens publicly. CDP, noVNC, ttyd and Playwright UI bind to 127.0.0.1, and Remote Control is outbound HTTPS only. ngrok tunnels open only when you run `ngrok up` or approve `ngrok_up` in a session, and viewer and app tunnels require basic auth (the approved tool returns the login so you can sign in from your phone).
|
|
207
227
|
- `ANTHROPIC_API_KEY` and similar are stripped from sessions (an API key would bypass the claude.ai login that Remote Control needs), and `secrets set` refuses to store them.
|
|
208
228
|
- `docker` access is root-equivalent on Linux. Leave the `docker` capability off on a device you share.
|
|
209
229
|
|
|
@@ -223,7 +243,7 @@ Logs: `harness-device logs <project|proc-name|service> [-f]`.
|
|
|
223
243
|
## What it deliberately does NOT do
|
|
224
244
|
|
|
225
245
|
- **Install Dokploy, or any server software beyond the tools above.** Dokploy is used through the API of your existing deployment.
|
|
226
|
-
- **Open public URLs on its own.** ngrok stays off until you
|
|
246
|
+
- **Open public URLs on its own.** ngrok stays off until you open a tunnel or approve the agent's `ngrok_up` request.
|
|
227
247
|
- **Replace a conversation silently.** A failing slot is flagged; only `session reset` starts a new one.
|
|
228
248
|
- **Sandbox the agent.** It runs as your user, with the approvals above.
|
|
229
249
|
- **Support Windows, or Linux without systemd and apt** (yet).
|
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
|
@@ -75,7 +75,24 @@ ${cfg.SERVE_MODE === 'server'
|
|
|
75
75
|
- A one-off process that only needs to outlive this turn can go in a plain window: \`tmux new-window -d -t ${cfg.SESSION}: -n tmp-<name> -c <dir> '<command>'\` (gone after a reboot).
|
|
76
76
|
- Docker containers you start: use \`--restart unless-stopped\` (compose: \`restart: unless-stopped\`) so they come back after a reboot.
|
|
77
77
|
- \`harness-device status\` shows sessions, processes and services; \`harness-device events\` shows what was restored after the last restart.
|
|
78
|
-
- \`sudo\` is denied. If something needs root, tell the user the exact command
|
|
78
|
+
- \`sudo\` is denied. If something needs root, tell the user the exact command.
|
|
79
|
+
|
|
80
|
+
### Changing the device: only through its tools
|
|
81
|
+
The user is usually remote (phone, claude.ai) and can't type on this machine. Everything you change on the device goes through a harness-device tool, which asks the user's approval right here in the session:
|
|
82
|
+
- Settings: \`config_get\` / \`config_set\` (MCP) or \`harness-device config set KEY=VALUE\`. **Never edit files under \`~/.harness-device\`** (config.env, projects.tsv, ngrok files, state, logs) or the service files (systemd units, LaunchAgents), and never copy or back them up by hand.
|
|
83
|
+
- Long-running processes: \`proc_add\` / \`proc_remove\`. Public URLs: \`ngrok_up\` / \`ngrok_down\`.
|
|
84
|
+
- Put your own files (test pages, scripts, data) in the project folder, never in the device home.
|
|
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
|
+
- 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.`,
|
|
79
96
|
},
|
|
80
97
|
|
|
81
98
|
system: {
|
|
@@ -107,7 +124,7 @@ ${cfg.SERVE_MODE === 'server'
|
|
|
107
124
|
This is a Mac: browsers and headed tests open on its real screen, which the user watches with macOS Screen Sharing (through \`harness-device tunnel\`). This tmux session is viewable read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`.
|
|
108
125
|
- Screenshot of the screen: the \`screenshot\` MCP tool, or \`screencapture -x /tmp/screen.png\`.`
|
|
109
126
|
: `## Display and live viewers
|
|
110
|
-
A virtual display \`:${cfg.DISPLAY_NUM}\` is always on (\`DISPLAY\` is already set). The user watches it at noVNC \`http://127.0.0.1:${cfg.NOVNC_PORT}/vnc.html\` and this tmux session read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`, over an SSH tunnel (\`harness-device tunnel\`) or
|
|
127
|
+
A virtual display \`:${cfg.DISPLAY_NUM}\` is always on (\`DISPLAY\` is already set). The user watches it at noVNC \`http://127.0.0.1:${cfg.NOVNC_PORT}/vnc.html\` and this tmux session read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`, over an SSH tunnel (\`harness-device tunnel\`) or a public URL from the \`ngrok_up\` tool.
|
|
111
128
|
- Anything headed you start (browsers, Electron, Playwright \`--headed\`) appears there, so the user can see progress.
|
|
112
129
|
- Screenshot of the whole display: the \`screenshot\` MCP tool, or \`import -display :${cfg.DISPLAY_NUM} -window root /tmp/screen.png\`.`,
|
|
113
130
|
},
|
|
@@ -201,7 +218,7 @@ Deployments go through the user's Dokploy at ${cfg.DOKPLOY_URL || '(DOKPLOY_URL
|
|
|
201
218
|
{ name: 'ngrok authtoken', ok: fs.existsSync(ctx.paths.ngrokToken), warn: true, fix: 'harness-device ngrok token' },
|
|
202
219
|
],
|
|
203
220
|
docs: () => `## ngrok
|
|
204
|
-
Public URLs are off by default.
|
|
221
|
+
Public URLs are off by default. To open one, call \`ngrok_up\`: the user approves it here. Examples: \`{"ports":[3000]}\` exposes a dev server (registered with \`proc_add\` from the project folder), \`{"tunnels":["ttyd"]}\` the read-only terminal view. The result has the URL and, for tunnels behind a login, the user name and password: give both to the user. A free ngrok plan has one URL, so open one tunnel at a time. Check with \`ngrok_status\`; close everything with \`ngrok_down\` when the user is done.`,
|
|
205
222
|
},
|
|
206
223
|
|
|
207
224
|
ollama: {
|
package/src/cli.js
CHANGED
|
@@ -3,7 +3,7 @@ import os from 'node:os';
|
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import readline from 'node:readline';
|
|
5
5
|
import { spawnSync } from 'node:child_process';
|
|
6
|
-
import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths } from './config.js';
|
|
6
|
+
import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths, SETTABLE_KEYS, setConfigValue } from './config.js';
|
|
7
7
|
import { ORDER, CAPABILITIES } from './capabilities.js';
|
|
8
8
|
import { loadContext } from './context.js';
|
|
9
9
|
import { install, uninstall } from './install.js';
|
|
@@ -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)
|
|
@@ -40,8 +42,12 @@ ${color.bold('Device')}
|
|
|
40
42
|
status [--json] sessions, processes, services, viewers
|
|
41
43
|
tunnel ssh command to watch the display, tmux and Playwright UI
|
|
42
44
|
secrets set <KEY> | list | rm <KEY> API keys for MCP servers (kept out of agent sessions)
|
|
43
|
-
|
|
45
|
+
config get [KEY] | set KEY=VALUE settings a remote session may change (ngrok, Dokploy filters, transcript days)
|
|
46
|
+
ngrok token | up [viewers|apps|all|<tunnel>]... [--port 8099] | down | status
|
|
44
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)
|
|
45
51
|
mcp run the harness-device MCP server (stdio)
|
|
46
52
|
|
|
47
53
|
${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
@@ -52,8 +58,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
52
58
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
53
59
|
`;
|
|
54
60
|
|
|
55
|
-
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'json', 'purge', 'force', 'follow', 'help', 'version'];
|
|
56
|
-
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl'];
|
|
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'];
|
|
57
63
|
|
|
58
64
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
59
65
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -123,6 +129,11 @@ function setSecret(file, key, value) {
|
|
|
123
129
|
|
|
124
130
|
function printStatus(s) {
|
|
125
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
|
+
}
|
|
126
137
|
console.log(color.bold('\nsessions'));
|
|
127
138
|
if (!s.sessions.length) console.log(color.dim(' none (harness-device project add name:/dir)'));
|
|
128
139
|
for (const x of s.sessions) {
|
|
@@ -138,7 +149,6 @@ function printStatus(s) {
|
|
|
138
149
|
console.log(' ' + s.services.map((x) => `${x.state === 'active' ? color.green('●') : color.red('○')} ${x.unit.replace(/^harness-/, '')}`).join(' '));
|
|
139
150
|
console.log(color.bold('\nviewers') + color.dim(' (127.0.0.1; harness-device tunnel)'));
|
|
140
151
|
console.log(` display ${s.viewers.display}\n tmux ${s.viewers.tmux}`);
|
|
141
|
-
console.log(`\n${color.dim(s.load)}`);
|
|
142
152
|
if (s.browser) console.log(color.dim(`browser: ${s.browser}`));
|
|
143
153
|
}
|
|
144
154
|
|
|
@@ -180,7 +190,54 @@ export async function main(argv) {
|
|
|
180
190
|
|
|
181
191
|
case 'install': {
|
|
182
192
|
const ctx = loadContext(env, { dryRun: !!f.dryRun });
|
|
183
|
-
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
|
+
}
|
|
184
241
|
}
|
|
185
242
|
|
|
186
243
|
case 'uninstall':
|
|
@@ -230,6 +287,7 @@ export async function main(argv) {
|
|
|
230
287
|
return;
|
|
231
288
|
}
|
|
232
289
|
if (sub === 'new') {
|
|
290
|
+
await resources.gate(ctx, { force: !!f.force, what: 'a new session' });
|
|
233
291
|
const r = state.newSlot(ctx, rest[0]);
|
|
234
292
|
log.ok(`${rest[0]} slot ${r.slot}: conversation ${r.id} (window ${state.windowName(rest[0], r.slot)})`);
|
|
235
293
|
return state.applyLayout(ctx);
|
|
@@ -255,6 +313,7 @@ export async function main(argv) {
|
|
|
255
313
|
const [name, dir, ...cmdParts] = rest;
|
|
256
314
|
if (!cmdParts.length) throw new Error("usage: proc add <name> <dir> '<command>'");
|
|
257
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`) });
|
|
258
317
|
state.addProc(ctx, name, path.resolve(dir), cmdParts.join(' '));
|
|
259
318
|
return log.ok(`proc ${name} registered; running in tmux window proc-${name}`);
|
|
260
319
|
}
|
|
@@ -299,6 +358,27 @@ export async function main(argv) {
|
|
|
299
358
|
return log.info(`Then open:\n display ${v.display}\n tmux (r/o) ${v.tmux}\n Playwright ${v.playwrightUi} (while hd-pw-live ui runs)`);
|
|
300
359
|
}
|
|
301
360
|
|
|
361
|
+
case 'config': {
|
|
362
|
+
if (sub === 'set') {
|
|
363
|
+
const kv = rest.join(' ');
|
|
364
|
+
const eq = kv.indexOf('=');
|
|
365
|
+
if (eq < 1) throw new Error('Usage: harness-device config set KEY=VALUE');
|
|
366
|
+
const r = setConfigValue(kv.slice(0, eq).trim(), kv.slice(eq + 1), env);
|
|
367
|
+
log.ok(`${r.key}=${r.value}`);
|
|
368
|
+
if (r.needsInstall) log.info('Applies at the next: harness-device install');
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (sub === 'get' || !sub) {
|
|
372
|
+
const { cfg } = loadConfig(env);
|
|
373
|
+
for (const k of rest.length ? rest : Object.keys(SETTABLE_KEYS)) {
|
|
374
|
+
if (!Object.prototype.hasOwnProperty.call(SETTABLE_KEYS, k)) throw new Error(`${k} is not a settable key (${Object.keys(SETTABLE_KEYS).join(', ')})`);
|
|
375
|
+
console.log(`${k}=${cfg[k] ?? ''}`);
|
|
376
|
+
}
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
throw new Error('Usage: harness-device config get [KEY] | set KEY=VALUE');
|
|
380
|
+
}
|
|
381
|
+
|
|
302
382
|
case 'secrets': {
|
|
303
383
|
const p = getPaths(env);
|
|
304
384
|
if (sub === 'set') {
|
|
@@ -325,27 +405,13 @@ export async function main(argv) {
|
|
|
325
405
|
return log.ok('ngrok authtoken saved. Open tunnels with: harness-device ngrok up viewers');
|
|
326
406
|
}
|
|
327
407
|
if (sub === 'up') {
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
if (
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
ctx.platform.ngrokUp(ctx);
|
|
336
|
-
// The agent needs a few seconds to connect; wait for every tunnel (up to 30 s).
|
|
337
|
-
let s = { running: false, tunnels: [] };
|
|
338
|
-
for (let i = 0; i < 30; i++) {
|
|
339
|
-
await new Promise((r) => setTimeout(r, 1000));
|
|
340
|
-
s = await device.ngrokStatus();
|
|
341
|
-
if (s.tunnels.length >= names.length) break;
|
|
342
|
-
}
|
|
343
|
-
for (const t of s.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
|
|
344
|
-
const shared = ngrok.sharedUrls(s.tunnels);
|
|
345
|
-
if (shared.length) log.warn(`Your ngrok plan gives one URL, so ${shared.join(', ')} share it and each request goes to either at random. Open one at a time (e.g. harness-device ngrok up ttyd), or reserve more domains.`);
|
|
346
|
-
if (s.running && s.tunnels.length < names.length) log.warn(`only ${s.tunnels.length} of ${names.length} tunnels are up yet; check: harness-device ngrok status, harness-device logs ngrok`);
|
|
347
|
-
if (names.some((n) => ['novnc', 'ttyd', 'pwui'].includes(n))) log.info(color.dim(` viewer login: ${ctx.cfg.NGROK_VIEWER_USER} / (NGROK_VIEWER_PASS in ${p.config})`));
|
|
348
|
-
return log.ok(s.running ? `ngrok up (survives reboots until: harness-device ngrok down)` : 'ngrok did not start yet; check: harness-device logs ngrok');
|
|
408
|
+
const ports = f.port ? String(f.port).split(',') : [];
|
|
409
|
+
const r = await device.ngrokUp(ctx, { tunnels: rest, ports });
|
|
410
|
+
for (const t of r.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
|
|
411
|
+
if (r.shared.length) log.warn(`Your ngrok plan gives one URL, so ${r.shared.join(', ')} share it and each request goes to either at random. Open one at a time (e.g. harness-device ngrok up ttyd), or reserve more domains.`);
|
|
412
|
+
if (r.running && r.missing.length) log.warn(`not up yet: ${r.missing.join(', ')}; check: harness-device ngrok status, harness-device logs ngrok`);
|
|
413
|
+
if (r.login) log.info(color.dim(` login for ${r.login.for.join(', ')}: ${r.login.user} / (NGROK_VIEWER_PASS in ${p.config})`));
|
|
414
|
+
return log.ok(r.running ? `ngrok up (survives reboots until: harness-device ngrok down)` : 'ngrok did not start yet; check: harness-device logs ngrok');
|
|
349
415
|
}
|
|
350
416
|
if (sub === 'down') {
|
|
351
417
|
ctx.platform.ngrokDown(ctx);
|
|
@@ -392,3 +458,25 @@ export async function main(argv) {
|
|
|
392
458
|
throw new Error(`Unknown command "${cmd}". Run: harness-device help`);
|
|
393
459
|
}
|
|
394
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
|
|
@@ -240,3 +259,52 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
|
|
|
240
259
|
export function renderProjectsTsv(cfg) {
|
|
241
260
|
return projects(cfg).map((p) => `${p.name}\t${p.dir}`).join('\n') + (projects(cfg).length ? '\n' : '');
|
|
242
261
|
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Settings an agent may change from a remote session (each call needs the
|
|
265
|
+
* user's approval there). Secrets, capabilities, projects and service ports
|
|
266
|
+
* stay with `init`/`install`/`secrets` on the machine.
|
|
267
|
+
*/
|
|
268
|
+
export const SETTABLE_KEYS = {
|
|
269
|
+
NGROK_APP_PORTS: 'comma-separated local ports that `ngrok up apps` exposes',
|
|
270
|
+
NGROK_APPS_PUBLIC: '1 = app tunnels without the viewer login, 0 = behind it (default)',
|
|
271
|
+
NGROK_DOMAIN: 'your reserved ngrok domain, or empty',
|
|
272
|
+
DOKPLOY_TOOL_PRESET: 'Dokploy MCP tool preset (needs install to apply)',
|
|
273
|
+
DOKPLOY_ENABLED_TAGS: 'Dokploy MCP tool categories to load (needs install to apply)',
|
|
274
|
+
DOKPLOY_DISABLED_TAGS: 'Dokploy MCP tool categories to drop (needs install to apply)',
|
|
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',
|
|
283
|
+
};
|
|
284
|
+
const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS|AUTO_UPGRADE|RESOURCE_GUARD)/;
|
|
285
|
+
|
|
286
|
+
/** Validate and save one settable key; returns { key, value, needsInstall }. */
|
|
287
|
+
export function setConfigValue(key, value, env = process.env) {
|
|
288
|
+
if (!Object.prototype.hasOwnProperty.call(SETTABLE_KEYS, key)) {
|
|
289
|
+
const hint = /KEY|TOKEN|SECRET|PASS/i.test(key) ? 'secrets are entered on the machine: harness-device secrets set KEY'
|
|
290
|
+
: 'capabilities, projects and ports change with harness-device init + install on the machine';
|
|
291
|
+
throw new Error(`${key} can't be changed from a session (${hint}). Settable: ${Object.keys(SETTABLE_KEYS).join(', ')}`);
|
|
292
|
+
}
|
|
293
|
+
let v = String(value ?? '').trim();
|
|
294
|
+
if (key === 'NGROK_APP_PORTS') v = mergePorts('', v);
|
|
295
|
+
if (key === 'NGROK_APPS_PUBLIC' && !['0', '1'].includes(v)) throw new Error('NGROK_APPS_PUBLIC must be 0 or 1');
|
|
296
|
+
if (key === 'NGROK_DOMAIN' && v && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(v)) throw new Error('NGROK_DOMAIN must be a host name such as my-app.ngrok-free.app');
|
|
297
|
+
const cfg = { ...loadConfig(env).cfg, [key]: v };
|
|
298
|
+
const errs = validateConfig(cfg, env);
|
|
299
|
+
if (errs.length) throw new Error(errs.join(' '));
|
|
300
|
+
saveConfig(cfg, env);
|
|
301
|
+
return { key, value: v, needsInstall: NEEDS_INSTALL.test(key) };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** "3000,5173" + [8099] → "3000,5173,8099" (deduplicated, each 1-65535). */
|
|
305
|
+
export function mergePorts(existing, add) {
|
|
306
|
+
const list = [...String(existing || '').split(','), ...(Array.isArray(add) ? add : String(add || '').split(','))]
|
|
307
|
+
.map((x) => String(x).trim()).filter(Boolean);
|
|
308
|
+
for (const p of list) if (!/^\d+$/.test(p) || Number(p) < 1 || Number(p) > 65535) throw new Error(`Not a port: ${p}`);
|
|
309
|
+
return [...new Set(list.map(Number))].join(',');
|
|
310
|
+
}
|
package/src/device.js
CHANGED
|
@@ -6,6 +6,9 @@ import path from 'node:path';
|
|
|
6
6
|
import { spawn } from 'node:child_process';
|
|
7
7
|
import { capture, ok, httpJson, which } from './util.js';
|
|
8
8
|
import { listSessions, listProcs, recentEvents } from './state.js';
|
|
9
|
+
import { loadConfig, saveConfig, mergePorts } from './config.js';
|
|
10
|
+
import * as ngrok from './ngrok.js';
|
|
11
|
+
import * as resources from './resources.js';
|
|
9
12
|
|
|
10
13
|
const short = (u) => u.replace(/^harness-/, '');
|
|
11
14
|
const logical = (name) => (name.startsWith('harness-') ? name : `harness-${name}`).replace(/\.(service|timer)$/, '');
|
|
@@ -51,8 +54,7 @@ export async function status(ctx) {
|
|
|
51
54
|
services: serviceStates(ctx),
|
|
52
55
|
browser: cdp ? cdp.Browser : null,
|
|
53
56
|
viewers: viewers(ctx.cfg, ctx.platform),
|
|
54
|
-
|
|
55
|
-
disk: capture('df', ['-h', '/']),
|
|
57
|
+
resources: await resources.sample(ctx, { quick: true }),
|
|
56
58
|
};
|
|
57
59
|
}
|
|
58
60
|
|
|
@@ -60,7 +62,7 @@ export async function status(ctx) {
|
|
|
60
62
|
export function logs(ctx, target, lines = 100) {
|
|
61
63
|
const n = Math.max(1, Math.min(2000, Number(lines) || 100));
|
|
62
64
|
const proj = ctx.projects.find((p) => p.name === target);
|
|
63
|
-
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)) {
|
|
64
66
|
const file = path.join(ctx.paths.logs, proj ? `rc-${proj.name}.log` : `${target}.log`);
|
|
65
67
|
return fs.existsSync(file) ? capture('tail', ['-n', String(n), file]) : `(no log yet: ${file})`;
|
|
66
68
|
}
|
|
@@ -125,3 +127,43 @@ export async function ngrokStatus() {
|
|
|
125
127
|
if (!j) return { running: false, tunnels: [] };
|
|
126
128
|
return { running: true, tunnels: (j.tunnels || []).map((t) => ({ name: t.name, url: t.public_url, addr: t.config && t.config.addr })) };
|
|
127
129
|
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Open ngrok tunnels (groups or single names), optionally adding app ports
|
|
133
|
+
* first. Shared by `harness-device ngrok up` and the ngrok_up MCP tool.
|
|
134
|
+
* Returns { tunnels, shared, missing, login } — login only for tunnels behind basic auth.
|
|
135
|
+
*/
|
|
136
|
+
export async function ngrokUp(ctx, { tunnels = [], ports = [] } = {}) {
|
|
137
|
+
const p = ctx.paths;
|
|
138
|
+
if (!ctx.caps.some((c) => c.id === 'ngrok')) throw new Error('The ngrok capability is off on this device (turn it on with harness-device init --with ngrok + install, on the machine).');
|
|
139
|
+
if (!fs.existsSync(p.ngrokToken)) throw new Error('No ngrok authtoken on this device yet (harness-device ngrok token, on the machine).');
|
|
140
|
+
let { cfg } = loadConfig(ctx.env);
|
|
141
|
+
const file = fs.existsSync(p.config) ? fs.readFileSync(p.config, 'utf8') : '';
|
|
142
|
+
let dirty = !/^NGROK_VIEWER_PASS=/m.test(file); // a generated password must be saved, or the next run makes another
|
|
143
|
+
if (ports.length) {
|
|
144
|
+
const merged = mergePorts(cfg.NGROK_APP_PORTS, ports);
|
|
145
|
+
if (merged !== String(cfg.NGROK_APP_PORTS || '')) { cfg = { ...cfg, NGROK_APP_PORTS: merged }; dirty = true; }
|
|
146
|
+
}
|
|
147
|
+
if (dirty) saveConfig(cfg, ctx.env);
|
|
148
|
+
const want = tunnels.length ? tunnels : ports.length ? ports.map((x) => `app${Number(x)}`) : ['viewers'];
|
|
149
|
+
const names = ngrok.selectTunnels(cfg, want, ctx.platform.id);
|
|
150
|
+
const write = (f, body) => { fs.writeFileSync(f + '.tmp', body, { mode: 0o600 }); fs.renameSync(f + '.tmp', f); };
|
|
151
|
+
write(p.ngrokYml, ngrok.renderNgrokYml(cfg, fs.readFileSync(p.ngrokToken, 'utf8').trim(), ctx.platform.id));
|
|
152
|
+
write(p.ngrokEnv, ngrok.renderNgrokEnv(names));
|
|
153
|
+
ctx.platform.ngrokUp(ctx);
|
|
154
|
+
let s = { running: false, tunnels: [] };
|
|
155
|
+
for (let i = 0; i < 30; i++) {
|
|
156
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
157
|
+
s = await ngrokStatus();
|
|
158
|
+
if (s.tunnels.length >= names.length) break;
|
|
159
|
+
}
|
|
160
|
+
const all = Object.assign({}, ...Object.values(ngrok.tunnels(cfg, ctx.platform.id)));
|
|
161
|
+
const guarded = names.filter((n) => all[n] && all[n].basic_auth);
|
|
162
|
+
return {
|
|
163
|
+
running: s.running,
|
|
164
|
+
tunnels: s.tunnels,
|
|
165
|
+
shared: ngrok.sharedUrls(s.tunnels),
|
|
166
|
+
missing: names.filter((n) => !s.tunnels.some((t) => t.name === n)),
|
|
167
|
+
login: guarded.length ? { user: cfg.NGROK_VIEWER_USER, password: cfg.NGROK_VIEWER_PASS, for: guarded } : null,
|
|
168
|
+
};
|
|
169
|
+
}
|
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.
|