@dreamtree-org/harness-device 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/package.json +1 -1
- package/sh/bin/hd-proc-loop +10 -1
- package/sh/bin/hd-serve-claude +3 -0
- package/sh/bin/hd-tmux-layout +3 -0
- package/sh/bin/hd-watchdog +13 -0
- package/src/capabilities.js +19 -1
- package/src/cleanup.js +195 -0
- package/src/cli.js +54 -10
- package/src/config.js +55 -1
- package/src/container.js +26 -0
- package/src/context.js +4 -1
- package/src/device.js +21 -1
- package/src/doctor.js +10 -0
- package/src/limits.js +248 -0
- package/src/mcp/interact.js +130 -0
- package/src/mcp/server.js +71 -46
- package/src/platform/darwin.js +2 -1
- package/src/platform/linux.js +2 -0
- package/src/providers/claude.js +4 -1
- package/src/resources.js +3 -2
- package/src/serve/cli.js +129 -0
- package/src/serve/http.js +120 -0
- package/src/serve/oauth.js +235 -0
- package/src/serve/scopes.js +37 -0
- package/src/state.js +15 -0
- package/templates/systemd/harness-chromium.service +4 -0
- package/templates/systemd/harness-serve.service +16 -0
- package/templates/systemd/harness-tmux.service +4 -0
package/README.md
CHANGED
|
@@ -158,6 +158,43 @@ New work from a session waits while CPU, RAM or disk is critical, and is refused
|
|
|
158
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
159
|
- The heal job records every move into or out of critical in `events`.
|
|
160
160
|
|
|
161
|
+
### Safe maximums
|
|
162
|
+
|
|
163
|
+
On top of the guard, what harness-device runs has hard limits, worked out from the machine. `harness-device limits` shows them against current use.
|
|
164
|
+
- **Defaults on an 8 GB, 4-core server:**
|
|
165
|
+
- 1 GB of RAM always kept free for the OS, Docker and other apps.
|
|
166
|
+
- About 4.8 GB for all sessions, processes and the browser together.
|
|
167
|
+
- 2 GB and 2 cores per registered process.
|
|
168
|
+
- About 1.5 GB for the browser.
|
|
169
|
+
- 4 sessions and 6 registered processes at most.
|
|
170
|
+
- **Linux:** the kernel holds them. Registered processes run in their own systemd scope (`MemoryMax`/`CPUQuota`), and Chromium's unit has `MemoryMax`. `doctor` checks that the user manager can do this.
|
|
171
|
+
- **Everywhere:** a watchdog checks every 30 seconds. A registered process or the browser over its limit for 3 readings is stopped and restarted. Over the total, the largest registered process goes first. Agent sessions and Docker or Dokploy apps are never stopped.
|
|
172
|
+
- **Containers with no memory limit** appear in `docker_summary`. `docker_limit` sets one; Dokploy apps get theirs in Dokploy.
|
|
173
|
+
- **Settings:** `RES_RESERVE_MEM`, `RES_HARNESS_MEM_MAX`, `RES_PROC_MEM_MAX`, `RES_PROC_CPU_MAX`, `RES_BROWSER_MEM_MAX`, `MAX_SESSIONS`, `MAX_PROCS`, `RES_WATCHDOG`. Memory values take forms such as `25%`, `1536`, `512M` or `1.5G`.
|
|
174
|
+
|
|
175
|
+
### Remote sessions never wait on this machine
|
|
176
|
+
|
|
177
|
+
In a Remote Control session, a tool that needs your OK (stopping a process, closing ngrok, an upgrade, a restart, a cleanup) does nothing on the first call. Instead the agent asks you with AskUserQuestion, so the question reaches your phone. It then calls the tool again with a one-use `confirm_token` tied to exactly that action. Local terminal sessions may show a form instead; one left unanswered falls back to the same question after `ELICIT_TIMEOUT_SECONDS`. `ASK_MODE=tool|elicit|auto` overrides the choice.
|
|
178
|
+
|
|
179
|
+
Disk running out? `harness-device cleanup`, or the `disk_cleanup` tool, lists what can go safely: Docker build cache, dangling images, old unmanaged stopped containers, package caches, test reports and logs. It shows sizes, and `--apply` removes the items you choose. Volumes and databases are never removed.
|
|
180
|
+
|
|
181
|
+
### Serve the tools over HTTP (any MCP client)
|
|
182
|
+
|
|
183
|
+
`harness-device serve` serves the device's MCP tools over HTTP (Streamable HTTP) with OAuth 2.1. A claude.ai custom connector, other agents and scripts can then use them, not only the sessions on this machine.
|
|
184
|
+
- **Approving apps:** each app registers itself. You approve it on a consent page with the owner password (`harness-device serve password`) and choose its permissions:
|
|
185
|
+
- `device:read`: status, logs, resources.
|
|
186
|
+
- `device:operate`: processes, services, ngrok, cleanup.
|
|
187
|
+
- `device:admin`: upgrade, restart, settings.
|
|
188
|
+
- **Tokens:** an app only sees the tools its permissions cover. Tokens are stored hashed. List apps with `serve clients`, and remove one and its tokens with `serve revoke <id>`.
|
|
189
|
+
- **As a service:** add `serve` to the capabilities and `install`. It listens on 127.0.0.1:7700 (`SERVE_HOST`, `SERVE_PORT`).
|
|
190
|
+
- **Behind Dokploy:**
|
|
191
|
+
1. `harness-device serve expose --domain mcp.example.com` writes a Traefik route into Dokploy and binds serve where only Traefik can reach it.
|
|
192
|
+
2. Point DNS at the server.
|
|
193
|
+
3. Run `install`.
|
|
194
|
+
4. Add `https://mcp.example.com/mcp` to your MCP client.
|
|
195
|
+
|
|
196
|
+
**As a Dokploy app** (no host install): deploy `docker-compose.dokploy.yml` as a Compose app. Its comments list the environment variables and the domain. It serves a reduced set of tools: `resources`, `docker_summary`, `docker_limit` and `disk_cleanup` (Docker items), for the host's Docker, RAM, CPU and disk. Sessions, processes and the browser need the host install. The image is also built to `ghcr.io/dreamtree-org/harness-device` by `.github/workflows/image.yml`.
|
|
197
|
+
|
|
161
198
|
## Commands
|
|
162
199
|
|
|
163
200
|
| Command | What it does |
|
|
@@ -178,6 +215,9 @@ New work from a session waits while CPU, RAM or disk is critical, and is refused
|
|
|
178
215
|
| `ngrok token`, `ngrok up [viewers\|apps\|all\|<tunnel>] [--port 8099]`, `ngrok down`, `ngrok status` | Public URLs, off until you turn them on |
|
|
179
216
|
| `config get [KEY]`, `config set KEY=VALUE` | The settings a remote session may change (app ports, Dokploy tool filters, transcript days) |
|
|
180
217
|
| `mcp` | The harness-device MCP server (stdio) |
|
|
218
|
+
| `serve`, `serve password [--rotate]`, `serve clients`, `serve revoke <id>`, `serve expose --domain D` | The same tools over HTTP with OAuth, and its owner password, apps and Dokploy route |
|
|
219
|
+
| `limits [--enforce]` | Safe maximums against current use; `--enforce` runs one watchdog pass |
|
|
220
|
+
| `cleanup [--apply] [item…]` | What can be freed safely, with sizes; `--apply` removes it |
|
|
181
221
|
| `fleet add <name> <user@host>`, `fleet status`, `fleet run <name> <args>` | Many devices from one machine, over ssh |
|
|
182
222
|
| `uninstall [--purge]` | Remove services and agent wiring (`--purge` also deletes state and config) |
|
|
183
223
|
|
|
@@ -197,6 +237,7 @@ Pick them with `init --with`/`--without`, or edit `CAPABILITIES=` in `config.env
|
|
|
197
237
|
| `dokploy` | API only | API only | Dokploy MCP against your deployment (`DOKPLOY_URL` + `secrets set DOKPLOY_API_KEY`); nothing is installed |
|
|
198
238
|
| `graphify` | | | `@dreamtree-org/graphify` CLI; `graphify .` wires a project's graph MCP and hooks |
|
|
199
239
|
| `ngrok` | apt repo | Homebrew (Intel: ngrok's official release, into `~/.local/bin`) | Tunnels you open; the agent may only read them |
|
|
240
|
+
| `serve` | systemd unit | launchd agent | These tools over HTTP with OAuth (`harness-device serve`), for other MCP clients |
|
|
200
241
|
| `ollama` | ollama.com script | Homebrew (Intel: Ollama app) | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
|
|
201
242
|
|
|
202
243
|
Extra MCP servers for the agent: add `MCP_<name>=command args` lines to `config.env`. They run through `hd-with-secrets`, so API keys stay in `secrets.env`.
|
|
@@ -240,6 +281,7 @@ harness-device fleet status # every device: sessions, failing slots, serv
|
|
|
240
281
|
- 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).
|
|
241
282
|
- `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.
|
|
242
283
|
- `docker` access is root-equivalent on Linux. Leave the `docker` capability off on a device you share.
|
|
284
|
+
- `harness-device serve` listens on 127.0.0.1 unless you change it, and every MCP request needs an OAuth token that you approved with the owner password. Agents on the device can't run `harness-device serve` (its password and app approvals are yours). The container image mounts the Docker socket, which is root-equivalent, so give its apps `device:read` unless they need more.
|
|
243
285
|
|
|
244
286
|
## Troubleshooting
|
|
245
287
|
|
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.8",
|
|
4
4
|
"description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Partha Preetham Krishna",
|
package/sh/bin/hd-proc-loop
CHANGED
|
@@ -7,12 +7,21 @@ set -u
|
|
|
7
7
|
name="$1"
|
|
8
8
|
f="$HD_STATE/procs/$name"
|
|
9
9
|
hd_strip_anthropic
|
|
10
|
+
# Linux: run it in its own systemd scope so the kernel holds its safe maximum
|
|
11
|
+
# (RES_PROC_MEM_MAX / RES_PROC_CPU_MAX). Where that isn't available (macOS,
|
|
12
|
+
# no user cgroup delegation) the watchdog holds it instead.
|
|
13
|
+
scope=()
|
|
14
|
+
if [ "${HD_PLATFORM:-}" = linux ] && [ -n "${HD_PROC_MEM_MAX_MB:-}" ] && command -v systemd-run >/dev/null 2>&1 \
|
|
15
|
+
&& systemd-run --user --scope --quiet -p MemoryMax=64M true >/dev/null 2>&1; then
|
|
16
|
+
scope=(systemd-run --user --scope --quiet --collect --unit "harness-proc-$name-$$" \
|
|
17
|
+
-p "MemoryMax=${HD_PROC_MEM_MAX_MB}M" -p "MemoryHigh=$(( HD_PROC_MEM_MAX_MB * 9 / 10 ))M" -p "CPUQuota=${HD_PROC_CPU_MAX:-200}%" --)
|
|
18
|
+
fi
|
|
10
19
|
delay=2
|
|
11
20
|
while [ -f "$f.cmd" ] && [ ! -e "$HD_STATE/stopping" ]; do
|
|
12
21
|
cd "$(cat "$f.dir" 2>/dev/null || echo "$HOME")" || exit 1
|
|
13
22
|
started=$(date +%s)
|
|
14
23
|
hd_log "proc $name: $(cat "$f.cmd")"
|
|
15
|
-
bash -c "$(cat "$f.cmd")"
|
|
24
|
+
${scope[@]+"${scope[@]}"} bash -c "$(cat "$f.cmd")"
|
|
16
25
|
code=$?
|
|
17
26
|
[ -f "$f.cmd" ] || break
|
|
18
27
|
[ -e "$HD_STATE/stopping" ] && { hd_log "proc $name ended (device stopping)"; exit 0; }
|
package/sh/bin/hd-serve-claude
CHANGED
|
@@ -12,6 +12,9 @@ set -u
|
|
|
12
12
|
. "$(dirname "$0")/hd-lib.sh"
|
|
13
13
|
command -v claude >/dev/null 2>&1 || { echo "claude is not on PATH (install: curl -fsSL https://claude.ai/install.sh | bash)"; exit 127; }
|
|
14
14
|
name="$1"; id="${2:--}"
|
|
15
|
+
# The user reaches this session remotely: nothing may wait on this machine's
|
|
16
|
+
# terminal. Device tools and the resource hook read it (inherited by children).
|
|
17
|
+
export HD_REMOTE_CONTROL=1
|
|
15
18
|
if [ "$id" = - ]; then
|
|
16
19
|
exec claude remote-control --name "$name"
|
|
17
20
|
fi
|
package/sh/bin/hd-tmux-layout
CHANGED
|
@@ -64,6 +64,9 @@ if [ -d "$HD_STATE/procs" ]; then
|
|
|
64
64
|
done
|
|
65
65
|
fi
|
|
66
66
|
|
|
67
|
+
# The resource watchdog (safe maximums); not an rc-/proc- window, so never closed below.
|
|
68
|
+
ensure watchdog "$HOME" "$HD_HOME/logs/watchdog.log" "$bin/hd-watchdog"
|
|
69
|
+
|
|
67
70
|
while read -r win; do
|
|
68
71
|
case "$win" in
|
|
69
72
|
rc-*|proc-*) case "$want" in *" $win "*) ;; *) tmux kill-window -t "=$s:$win"; hd_log "closed window $win (removed)" ;; esac ;;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Holds the safe maximums (src/limits.js) every 30s: registered processes and
|
|
3
|
+
# the browser that stay over their limit are stopped (their loop restarts
|
|
4
|
+
# them, with backoff). Runs in the tmux window "watchdog"; hd-heal tops the
|
|
5
|
+
# window up if it dies. RES_WATCHDOG=off: it only measures.
|
|
6
|
+
set -u
|
|
7
|
+
. "$(dirname "$0")/hd-lib.sh"
|
|
8
|
+
while [ ! -e "$HD_STATE/stopping" ]; do
|
|
9
|
+
if [ ! -e "$HD_STATE/stopped" ] && [ ! -e "$HD_STATE/restarting" ]; then
|
|
10
|
+
"$HD_HOME/bin/harness-device" limits --enforce --quiet 2>&1 || hd_log "watchdog pass failed"
|
|
11
|
+
fi
|
|
12
|
+
sleep 30
|
|
13
|
+
done
|
package/src/capabilities.js
CHANGED
|
@@ -88,6 +88,8 @@ The user is usually remote (phone, claude.ai) and can't type on this machine. Ev
|
|
|
88
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
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
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
|
+
- **Safe maximums** (\`resources\` tool → limits, or \`harness-device limits\`): part of RAM is always kept free for the OS, Docker and other apps; each registered process and the browser have a RAM (and CPU) cap, and there is a cap on sessions and registered processes. One that stays over its cap is stopped and restarted (an event says so). If a dev server keeps being stopped, tell the user what it uses and ask (AskUserQuestion) whether to raise RES_PROC_MEM_MAX or reduce the work; never work around the cap. Containers without a memory limit show in \`docker_summary\`; offer \`docker_limit\` for them (Dokploy apps get their limit in Dokploy).
|
|
92
|
+
- **Freeing disk:** use the \`disk_cleanup\` tool (or \`harness-device cleanup\`). Call it without apply to list what can go and how big it is, ask the user which items with AskUserQuestion (multiSelect), then call it with apply=true and those items. It only removes caches and leftovers that rebuild themselves; never delete volumes, databases, Dokploy containers or project files to make room without asking about each one specifically.
|
|
91
93
|
- When it is only **high**, go ahead but prefer one heavy job at a time.
|
|
92
94
|
|
|
93
95
|
### Upgrades
|
|
@@ -211,6 +213,22 @@ Deployments go through the user's Dokploy at ${cfg.DOKPLOY_URL || '(DOKPLOY_URL
|
|
|
211
213
|
\`graphify\` is installed. In a project without \`graphify-out/graph.json\`, run \`graphify .\` once: it builds the graph and wires the project's \`.mcp.json\` and Claude hooks, so later sessions use the \`graphify\` MCP tools for search and blast-radius before reading files. \`graphify doctor\` checks freshness.`,
|
|
212
214
|
},
|
|
213
215
|
|
|
216
|
+
serve: {
|
|
217
|
+
label: 'MCP over HTTP with OAuth (harness-device serve): these tools for any MCP client, e.g. a claude.ai connector, through Dokploy/Traefik or ngrok',
|
|
218
|
+
units: { linux: ['harness-serve'], darwin: ['harness-serve'] },
|
|
219
|
+
checks: async (ctx) => {
|
|
220
|
+
const { readSecrets } = await import('./context.js');
|
|
221
|
+
return [
|
|
222
|
+
{ name: `serve on ${ctx.cfg.SERVE_HOST}:${ctx.cfg.SERVE_PORT}`, ok: await httpOk(`http://${ctx.cfg.SERVE_HOST}:${ctx.cfg.SERVE_PORT}/healthz`), fix: 'harness-device logs serve' },
|
|
223
|
+
{ name: 'owner password (SERVE_OWNER_PASSWORD)', ok: !!readSecrets(ctx.paths.secrets).SERVE_OWNER_PASSWORD, fix: 'harness-device serve password' },
|
|
224
|
+
{ name: 'public URL (SERVE_PUBLIC_URL)', ok: !!ctx.cfg.SERVE_PUBLIC_URL, warn: true, msg: ctx.cfg.SERVE_PUBLIC_URL || 'local only', fix: 'harness-device serve expose --domain mcp.example.com' },
|
|
225
|
+
...(ctx.cfg.SERVE_PUBLIC_URL ? [{ name: `reachable at ${ctx.cfg.SERVE_PUBLIC_URL}`, ok: await httpOk(`${ctx.cfg.SERVE_PUBLIC_URL.replace(/\/+$/, '')}/healthz`, 8000), warn: true, fix: 'check DNS and the Traefik route (harness-device serve expose)' }] : []),
|
|
226
|
+
];
|
|
227
|
+
},
|
|
228
|
+
docs: (cfg) => `## These tools over HTTP (harness-device serve)
|
|
229
|
+
The same device tools are served at \`${cfg.SERVE_PUBLIC_URL ? `${cfg.SERVE_PUBLIC_URL.replace(/\/+$/, '')}/mcp` : `http://${cfg.SERVE_HOST}:${cfg.SERVE_PORT}/mcp`}\` for other MCP clients (a claude.ai connector, other agents). Apps connect with OAuth: the device owner approves each one with the owner password and picks its scopes (device:read, device:operate, device:admin). The password, approving and revoking apps are the owner's, on the machine (\`harness-device serve password|clients|revoke\`); never ask for the password.`,
|
|
230
|
+
},
|
|
231
|
+
|
|
214
232
|
ngrok: {
|
|
215
233
|
label: 'ngrok tunnels (off until `harness-device ngrok up`)',
|
|
216
234
|
system: ['ngrok'],
|
|
@@ -234,7 +252,7 @@ Ollama serves \`http://127.0.0.1:11434\` (OpenAI-compatible at \`/v1\`). Models:
|
|
|
234
252
|
},
|
|
235
253
|
};
|
|
236
254
|
|
|
237
|
-
export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'ollama'];
|
|
255
|
+
export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'serve', 'ollama'];
|
|
238
256
|
|
|
239
257
|
/** Resolve the enabled set: config list + required + dependencies, in a stable order. */
|
|
240
258
|
export function resolveCapabilities(ids) {
|
package/src/cleanup.js
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// Safe disk cleanup: only things that rebuild themselves (caches, build
|
|
2
|
+
// cache, unused images, old reports and logs). Never a database, a volume,
|
|
3
|
+
// or anything Dokploy (or another orchestrator) owns.
|
|
4
|
+
//
|
|
5
|
+
// plan(ctx) → candidates with sizes (nothing is changed)
|
|
6
|
+
// apply(ctx, ids) → run the chosen ones, report what was freed
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { capture, which } from './util.js';
|
|
11
|
+
|
|
12
|
+
const STOPPED_DAYS = 7;
|
|
13
|
+
const BIG_LOG = 50 * 1024 * 1024;
|
|
14
|
+
const KEEP_LOG_TAIL = 5 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
/** "1.23GB", "512kB", "0B (virtual 1GB)" → bytes. */
|
|
17
|
+
export function parseSize(s) {
|
|
18
|
+
const m = String(s || '').match(/([\d.]+)\s*([kKMGT]?i?B)/);
|
|
19
|
+
if (!m) return 0;
|
|
20
|
+
const unit = m[2].replace('i', '').toUpperCase();
|
|
21
|
+
const mult = { B: 1, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12 }[unit] || 1;
|
|
22
|
+
return Math.round(parseFloat(m[1]) * mult);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const human = (b) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : b >= 1e6 ? `${(b / 1e6).toFixed(0)} MB` : `${Math.round(b / 1e3)} kB`);
|
|
26
|
+
|
|
27
|
+
function du(p, env) {
|
|
28
|
+
if (!p || !fs.existsSync(p)) return 0;
|
|
29
|
+
const out = capture('du', ['-sk', p], { env, timeout: 60000 });
|
|
30
|
+
return (parseInt(out, 10) || 0) * 1024;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Labels that mean someone else manages the container: never touch it. */
|
|
34
|
+
export const MANAGED = /dokploy|com\.docker\.swarm|com\.docker\.compose|coolify|traefik/i;
|
|
35
|
+
|
|
36
|
+
/** Stopped containers older than STOPPED_DAYS that nothing manages. */
|
|
37
|
+
export function staleContainers(lines, now = Date.now()) {
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const line of lines) {
|
|
40
|
+
let c;
|
|
41
|
+
try { c = JSON.parse(line); } catch { continue; }
|
|
42
|
+
if (MANAGED.test(c.Labels || '') || MANAGED.test(c.Names || '')) continue;
|
|
43
|
+
const created = Date.parse(String(c.CreatedAt || '').replace(/ [A-Z]{3,4}$/, '').replace(' ', 'T').replace(' ', ''));
|
|
44
|
+
if (!Number.isFinite(created) || now - created < STOPPED_DAYS * 864e5) continue;
|
|
45
|
+
out.push({ id: c.ID, name: c.Names, bytes: parseSize(c.Size) });
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function dockerItems(env) {
|
|
51
|
+
if (!which('docker', env)) return [];
|
|
52
|
+
const items = [];
|
|
53
|
+
const df = capture('docker', ['system', 'df', '--format', '{{json .}}'], { env, timeout: 60000 }).split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return {}; } });
|
|
54
|
+
const reclaim = (type) => parseSize((df.find((d) => d.Type === type) || {}).Reclaimable);
|
|
55
|
+
const cache = reclaim('Build Cache');
|
|
56
|
+
if (cache) {
|
|
57
|
+
items.push({ id: 'docker-build-cache', what: 'Docker build cache (rebuilt on the next build; builds are slower once)', bytes: cache,
|
|
58
|
+
run: () => capture('docker', ['builder', 'prune', '-af'], { env, timeout: 600000 }) });
|
|
59
|
+
}
|
|
60
|
+
const dangling = capture('docker', ['images', '-f', 'dangling=true', '--format', '{{.Size}}'], { env }).split('\n').filter(Boolean).reduce((a, s) => a + parseSize(s), 0);
|
|
61
|
+
if (dangling) {
|
|
62
|
+
items.push({ id: 'docker-dangling-images', what: 'Untagged (dangling) Docker images: old layers no container uses', bytes: dangling,
|
|
63
|
+
run: () => capture('docker', ['image', 'prune', '-f'], { env, timeout: 600000 }) });
|
|
64
|
+
}
|
|
65
|
+
const stale = staleContainers(capture('docker', ['ps', '-a', '--size', '--filter', 'status=exited', '--filter', 'status=created', '--format', '{{json .}}'], { env, timeout: 60000 }).split('\n').filter(Boolean));
|
|
66
|
+
if (stale.length) {
|
|
67
|
+
items.push({ id: 'docker-stale-containers', what: `${stale.length} stopped container(s) older than ${STOPPED_DAYS} days, not managed by Dokploy/compose/swarm: ${stale.map((c) => c.name).join(', ')}`,
|
|
68
|
+
bytes: stale.reduce((a, c) => a + c.bytes, 0),
|
|
69
|
+
run: () => capture('docker', ['rm', ...stale.map((c) => c.id)], { env, timeout: 120000 }) });
|
|
70
|
+
}
|
|
71
|
+
const vols = capture('docker', ['volume', 'ls', '-qf', 'dangling=true'], { env }).split('\n').filter(Boolean);
|
|
72
|
+
if (vols.length) {
|
|
73
|
+
items.push({ id: 'docker-unused-volumes', what: `${vols.length} Docker volume(s) no container uses. They can hold data (databases), so they are listed only, never removed here: ${vols.slice(0, 10).join(', ')}${vols.length > 10 ? ', …' : ''}`,
|
|
74
|
+
bytes: 0, listOnly: true });
|
|
75
|
+
}
|
|
76
|
+
return items;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function cacheItems(ctx) {
|
|
80
|
+
const env = ctx.env;
|
|
81
|
+
const items = [];
|
|
82
|
+
if (which('npm', env)) {
|
|
83
|
+
const dir = capture('npm', ['config', 'get', 'cache'], { env });
|
|
84
|
+
const bytes = du(dir, env);
|
|
85
|
+
if (bytes) items.push({ id: 'npm-cache', what: `npm download cache (${dir})`, bytes, run: () => capture('npm', ['cache', 'clean', '--force'], { env, timeout: 300000 }) });
|
|
86
|
+
}
|
|
87
|
+
if (which('pnpm', env)) {
|
|
88
|
+
const dir = capture('pnpm', ['store', 'path'], { env });
|
|
89
|
+
const bytes = du(dir, env);
|
|
90
|
+
if (bytes) items.push({ id: 'pnpm-store', what: `pnpm store: packages no project links any more (${dir}); frees part of this, the size is the whole store`, bytes, upTo: true, run: () => capture('pnpm', ['store', 'prune'], { env, timeout: 300000 }) });
|
|
91
|
+
}
|
|
92
|
+
for (const pip of ['pip3', 'pip']) {
|
|
93
|
+
if (!which(pip, env)) continue;
|
|
94
|
+
const dir = capture(pip, ['cache', 'dir'], { env });
|
|
95
|
+
const bytes = du(dir, env);
|
|
96
|
+
if (bytes) items.push({ id: 'pip-cache', what: `pip download cache (${dir})`, bytes, run: () => capture(pip, ['cache', 'purge'], { env, timeout: 300000 }) });
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
if (ctx.platform.id === 'linux' && which('journalctl', env)) {
|
|
100
|
+
const m = capture('journalctl', ['--user', '--disk-usage'], { env }).match(/take up ([\d.]+[KMGT]?)/);
|
|
101
|
+
const bytes = m ? parseSize(`${m[1]}B`) : 0;
|
|
102
|
+
if (bytes > 100e6) items.push({ id: 'user-journal', what: 'Your systemd user journal, trimmed to the newest 100 MB', bytes: bytes - 100e6, run: () => capture('journalctl', ['--user', '--vacuum-size=100M'], { env, timeout: 120000 }) });
|
|
103
|
+
}
|
|
104
|
+
return items;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Playwright output folders at the top of each project (re-created by the next run). */
|
|
108
|
+
function reportItems(ctx) {
|
|
109
|
+
const dirs = [];
|
|
110
|
+
for (const p of ctx.projects) for (const d of ['playwright-report', 'test-results', 'blob-report']) {
|
|
111
|
+
const full = path.join(p.dir, d);
|
|
112
|
+
if (fs.existsSync(full) && fs.statSync(full).isDirectory()) dirs.push(full);
|
|
113
|
+
}
|
|
114
|
+
const bytes = dirs.reduce((a, d) => a + du(d, ctx.env), 0);
|
|
115
|
+
if (!bytes) return [];
|
|
116
|
+
return [{ id: 'test-reports', what: `Playwright reports and test results: ${dirs.join(', ')}`, bytes,
|
|
117
|
+
run: () => dirs.forEach((d) => fs.rmSync(d, { recursive: true, force: true })) }];
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Rotated harness logs are removed; logs over 50 MB keep their last 5 MB. */
|
|
121
|
+
function logItems(ctx) {
|
|
122
|
+
const dir = ctx.paths.logs;
|
|
123
|
+
if (!fs.existsSync(dir)) return [];
|
|
124
|
+
const rotated = [];
|
|
125
|
+
const big = [];
|
|
126
|
+
for (const f of fs.readdirSync(dir)) {
|
|
127
|
+
const full = path.join(dir, f);
|
|
128
|
+
let st;
|
|
129
|
+
try { st = fs.statSync(full); } catch { continue; }
|
|
130
|
+
if (!st.isFile()) continue;
|
|
131
|
+
if (/\.(\d+|old|gz)$/.test(f)) rotated.push({ full, bytes: st.size });
|
|
132
|
+
else if (st.size > BIG_LOG) big.push({ full, bytes: st.size - KEEP_LOG_TAIL });
|
|
133
|
+
}
|
|
134
|
+
const all = [...rotated, ...big];
|
|
135
|
+
if (!all.length) return [];
|
|
136
|
+
return [{ id: 'harness-logs', what: `harness-device logs: ${rotated.length} rotated file(s) removed, ${big.length} large log(s) cut to their last 5 MB`,
|
|
137
|
+
bytes: all.reduce((a, x) => a + x.bytes, 0),
|
|
138
|
+
run: () => {
|
|
139
|
+
for (const r of rotated) fs.rmSync(r.full, { force: true });
|
|
140
|
+
for (const b of big) truncateKeepTail(b.full, KEEP_LOG_TAIL);
|
|
141
|
+
} }];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function truncateKeepTail(file, keep) {
|
|
145
|
+
const size = fs.statSync(file).size;
|
|
146
|
+
if (size <= keep) return;
|
|
147
|
+
const fd = fs.openSync(file, 'r+');
|
|
148
|
+
try {
|
|
149
|
+
const buf = Buffer.alloc(keep);
|
|
150
|
+
fs.readSync(fd, buf, 0, keep, size - keep);
|
|
151
|
+
fs.ftruncateSync(fd, 0);
|
|
152
|
+
fs.writeSync(fd, buf, 0, keep, 0);
|
|
153
|
+
} finally { fs.closeSync(fd); }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function freeBytes(ctx) {
|
|
157
|
+
const out = capture('df', ['-Pk', ctx.env.HD_HOST_ROOT || ctx.paths.home], { env: ctx.env }).split('\n')[1] || '';
|
|
158
|
+
return (parseInt(out.trim().split(/\s+/)[3], 10) || 0) * 1024;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Everything that could be cleaned, biggest first. Changes nothing. */
|
|
162
|
+
export function plan(ctx) {
|
|
163
|
+
const has = (id) => ctx.caps.some((c) => c.id === id);
|
|
164
|
+
// In a container only Docker's leftovers are the host's; its own caches are not.
|
|
165
|
+
const items = [
|
|
166
|
+
...(has('docker') ? dockerItems(ctx.env) : []),
|
|
167
|
+
...(ctx.env.HD_CONTAINER === '1' ? [] : [...cacheItems(ctx), ...reportItems(ctx), ...logItems(ctx)]),
|
|
168
|
+
].sort((a, b) => b.bytes - a.bytes);
|
|
169
|
+
return items;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The plan without its functions, for the agent and the CLI. */
|
|
173
|
+
export function describe(items) {
|
|
174
|
+
const sum = (xs) => xs.reduce((a, i) => a + i.bytes, 0);
|
|
175
|
+
const sure = sum(items.filter((i) => !i.listOnly && !i.upTo));
|
|
176
|
+
const maybe = sum(items.filter((i) => i.upTo));
|
|
177
|
+
return {
|
|
178
|
+
total: human(sure) + (maybe ? ` (plus up to ${human(maybe)})` : ''),
|
|
179
|
+
items: items.map((i) => ({ id: i.id, size: i.listOnly ? 'n/a (listed only)' : `${i.upTo ? '≤' : ''}${human(i.bytes)}`, what: i.what })),
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Run the chosen items (all cleanable ones when ids is empty). */
|
|
184
|
+
export function apply(ctx, ids = [], items = plan(ctx)) {
|
|
185
|
+
const unknown = ids.filter((id) => !items.some((i) => i.id === id));
|
|
186
|
+
if (unknown.length) throw new Error(`Not cleanable now: ${unknown.join(', ')}. Cleanable: ${items.filter((i) => !i.listOnly).map((i) => i.id).join(', ') || 'nothing'}`);
|
|
187
|
+
const chosen = items.filter((i) => !i.listOnly && (!ids.length || ids.includes(i.id)));
|
|
188
|
+
const before = freeBytes(ctx);
|
|
189
|
+
const done = [];
|
|
190
|
+
for (const i of chosen) {
|
|
191
|
+
try { i.run(); done.push({ id: i.id, ok: true }); } catch (e) { done.push({ id: i.id, ok: false, error: String(e.message || e) }); }
|
|
192
|
+
}
|
|
193
|
+
const after = freeBytes(ctx);
|
|
194
|
+
return { freed: human(Math.max(0, after - before)), done };
|
|
195
|
+
}
|
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, SETTABLE_KEYS, setConfigValue } from './config.js';
|
|
6
|
+
import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths, SETTABLE_KEYS, setConfigValue, setSecret } 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';
|
|
@@ -15,6 +15,8 @@ import * as fleet from './fleet.js';
|
|
|
15
15
|
import * as lifecycle from './lifecycle.js';
|
|
16
16
|
import * as resources from './resources.js';
|
|
17
17
|
import * as upgrader from './upgrade.js';
|
|
18
|
+
import * as cleanup from './cleanup.js';
|
|
19
|
+
import * as limits from './limits.js';
|
|
18
20
|
import { PKG, log, color, run, writeFile, capture } from './util.js';
|
|
19
21
|
|
|
20
22
|
const HELP = `${color.bold('harness-device')} ${PKG.version}: a reboot-proof dev device for remote AI agents (Claude Remote Control first)
|
|
@@ -47,6 +49,12 @@ ${color.bold('Device')}
|
|
|
47
49
|
ngrok token | up [viewers|apps|all|<tunnel>]... [--port 8099] | down | status
|
|
48
50
|
restart <service> restart one harness service (chromium, ttyd, ...)
|
|
49
51
|
resources [--json] CPU, RAM and disk now, with the guard's level (ok, high, critical)
|
|
52
|
+
serve [--host H] [--port P] the device's MCP tools over HTTP with OAuth (foreground; capability "serve" runs it as a service)
|
|
53
|
+
serve password [--rotate] show (or create/rotate) the owner password the OAuth consent page asks for
|
|
54
|
+
serve clients | serve revoke <id> apps that connected, with their scopes; revoke one and all its tokens
|
|
55
|
+
serve expose --domain D Traefik (Dokploy) route for https://D → this device's serve
|
|
56
|
+
limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
|
|
57
|
+
cleanup [--apply] [item...] [--json] what could be freed safely (caches, build cache, old reports/logs); --apply removes it
|
|
50
58
|
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
51
59
|
stop [--now] [--timeout 120] graceful shutdown: waits for agent turns to finish, ends sessions and processes
|
|
52
60
|
cleanly, saves the browser; stays stopped (also after reboots) until start
|
|
@@ -65,7 +73,7 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
65
73
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
66
74
|
`;
|
|
67
75
|
|
|
68
|
-
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart'];
|
|
76
|
+
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart', 'enforce', 'quiet'];
|
|
69
77
|
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
70
78
|
|
|
71
79
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
@@ -127,12 +135,6 @@ function refreshProjects(ctx) {
|
|
|
127
135
|
state.applyLayout(ctx);
|
|
128
136
|
}
|
|
129
137
|
|
|
130
|
-
function setSecret(file, key, value) {
|
|
131
|
-
const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter((l) => !l.startsWith(`${key}=`)) : [];
|
|
132
|
-
while (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
133
|
-
if (value != null) lines.push(`${key}='${value}'`);
|
|
134
|
-
writeFile(file, lines.join('\n') + '\n', { mode: 0o600 });
|
|
135
|
-
}
|
|
136
138
|
|
|
137
139
|
function printStatus(s) {
|
|
138
140
|
console.log(`${color.bold(s.device)} ${color.dim(`· ${s.provider} · ${s.serveMode} mode · ${s.capabilities.join(', ')}`)}`);
|
|
@@ -253,6 +255,42 @@ export async function main(argv) {
|
|
|
253
255
|
return f.json ? console.log(JSON.stringify(s, null, 2)) : console.log(resources.summary(s) + (s.reasons.length ? `\n ${s.reasons.join('\n ')}` : ''));
|
|
254
256
|
}
|
|
255
257
|
|
|
258
|
+
case 'limits': {
|
|
259
|
+
const ctx = loadContext(env);
|
|
260
|
+
if (f.enforce) {
|
|
261
|
+
const r = await limits.enforce(ctx);
|
|
262
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
263
|
+
for (const a of r.actions) log.warn(`stopped ${a.name}: ${a.reason}`);
|
|
264
|
+
if (!f.quiet && !r.actions.length) log.ok('all within limits');
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const r = limits.report(ctx);
|
|
268
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
269
|
+
for (const [k, v] of Object.entries(r)) console.log(`${k.padEnd(12)} ${Array.isArray(v) ? v.join(', ') : v}`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
case 'serve': {
|
|
274
|
+
const ctx = loadContext(env);
|
|
275
|
+
const serveCli = await import('./serve/cli.js');
|
|
276
|
+
return serveCli.run(ctx, sub, rest, f);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
case 'cleanup': {
|
|
280
|
+
const ctx = loadContext(env);
|
|
281
|
+
const items = cleanup.plan(ctx);
|
|
282
|
+
const ids = [sub, ...rest].filter(Boolean);
|
|
283
|
+
const r = f.apply ? cleanup.apply(ctx, ids, items) : cleanup.describe(items);
|
|
284
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
285
|
+
if (f.apply) {
|
|
286
|
+
state.event(ctx, `cleanup freed ${r.freed}: ${r.done.map((x) => x.id).join(', ')}`);
|
|
287
|
+
for (const x of r.done) (x.ok ? log.ok : log.warn)(`${x.id}${x.ok ? '' : `: ${x.error}`}`);
|
|
288
|
+
return log.ok(`freed ${r.freed}`);
|
|
289
|
+
}
|
|
290
|
+
for (const i of r.items) console.log(`${i.size.padStart(9)} ${i.id}\n ${color.dim(i.what)}`);
|
|
291
|
+
return console.log(`\n${r.total} can be freed. Run: harness-device cleanup --apply [item...]`);
|
|
292
|
+
}
|
|
293
|
+
|
|
256
294
|
case 'gate': {
|
|
257
295
|
const ctx = loadContext(env);
|
|
258
296
|
if (f.hook) return gateHook(ctx);
|
|
@@ -529,12 +567,18 @@ async function gateHook(ctx) {
|
|
|
529
567
|
const cmd = (input.tool_input && input.tool_input.command) || '';
|
|
530
568
|
if (resources.isLightCommand(cmd)) return;
|
|
531
569
|
const force = /(^|\s)HD_FORCE=1(\s|$)/.test(cmd);
|
|
570
|
+
// A remote user sees a silent wait as a hung session: refuse at once and
|
|
571
|
+
// let the agent ask them what to do instead.
|
|
572
|
+
const remote = ctx.env.HD_REMOTE_CONTROL === '1';
|
|
532
573
|
try {
|
|
533
|
-
await resources.gate(ctx, { force, quick: true, waitSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 0, 540), what: 'this command' });
|
|
574
|
+
await resources.gate(ctx, { force, quick: true, waitSeconds: remote ? 0 : Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 0, 540), what: 'this command' });
|
|
534
575
|
} catch (e) {
|
|
535
576
|
if (!(e instanceof resources.ResourceDenied)) return;
|
|
577
|
+
const next = remote
|
|
578
|
+
? ' Ask the user with AskUserQuestion whether to free resources first (disk_cleanup, stop a process, prune Docker) or try again later; do not retry in a loop.'
|
|
579
|
+
: ' Check with: harness-device resources.';
|
|
536
580
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
537
|
-
permissionDecisionReason: `${e.message}
|
|
581
|
+
permissionDecisionReason: `${e.message}${next}` } }));
|
|
538
582
|
}
|
|
539
583
|
} catch { /* fail open */ }
|
|
540
584
|
}
|
package/src/config.js
CHANGED
|
@@ -6,6 +6,7 @@ import fs from 'node:fs';
|
|
|
6
6
|
import os from 'node:os';
|
|
7
7
|
import path from 'node:path';
|
|
8
8
|
import crypto from 'node:crypto';
|
|
9
|
+
import * as limitsMod from './limits.js';
|
|
9
10
|
|
|
10
11
|
export const DEFAULT_CAPABILITIES = 'browser,playwright,display,shell,system,sqlite,docker,graphify';
|
|
11
12
|
export const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
|
|
@@ -73,6 +74,26 @@ export function defaults(env = process.env) {
|
|
|
73
74
|
RES_CPU_CRITICAL: '95',
|
|
74
75
|
RES_MEM_CRITICAL: '5',
|
|
75
76
|
RES_DISK_CRITICAL: '3',
|
|
77
|
+
// How device tools ask the user: auto (AskUserQuestion in Remote Control
|
|
78
|
+
// sessions, a form in local ones) | tool (always AskUserQuestion) | elicit.
|
|
79
|
+
ASK_MODE: 'auto',
|
|
80
|
+
ELICIT_TIMEOUT_SECONDS: '90',
|
|
81
|
+
// Safe maximums (empty = worked out from this machine's RAM and cores;
|
|
82
|
+
// see src/limits.js). Memory: 25% of RAM, 1536 (MB), 512M or 1.5G.
|
|
83
|
+
RES_RESERVE_MEM: '',
|
|
84
|
+
RES_HARNESS_MEM_MAX: '',
|
|
85
|
+
RES_PROC_MEM_MAX: '',
|
|
86
|
+
RES_PROC_CPU_MAX: '',
|
|
87
|
+
RES_BROWSER_MEM_MAX: '',
|
|
88
|
+
RES_CONTAINER_MEM_DEFAULT: '',
|
|
89
|
+
MAX_SESSIONS: '',
|
|
90
|
+
MAX_PROCS: '',
|
|
91
|
+
RES_WATCHDOG: 'on',
|
|
92
|
+
// `harness-device serve` (capability "serve"): MCP over HTTP with OAuth.
|
|
93
|
+
// Bind address, and the https URL clients use (Traefik/Dokploy or ngrok in front).
|
|
94
|
+
SERVE_HOST: '127.0.0.1',
|
|
95
|
+
SERVE_PORT: '7700',
|
|
96
|
+
SERVE_PUBLIC_URL: '',
|
|
76
97
|
};
|
|
77
98
|
}
|
|
78
99
|
|
|
@@ -184,6 +205,16 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
184
205
|
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
206
|
if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
|
|
186
207
|
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
208
|
+
errs.push(...limitsMod.validate(cfg));
|
|
209
|
+
if (!/^\d+$/.test(String(cfg.SERVE_PORT ?? '7700')) || Number(cfg.SERVE_PORT ?? 7700) < 1 || Number(cfg.SERVE_PORT ?? 7700) > 65535) errs.push('SERVE_PORT must be a port, 1-65535.');
|
|
210
|
+
if (cfg.SERVE_HOST !== undefined && !/^[A-Za-z0-9.:-]+$/.test(String(cfg.SERVE_HOST))) errs.push('SERVE_HOST must be an IP address or host name.');
|
|
211
|
+
if (cfg.SERVE_PUBLIC_URL) {
|
|
212
|
+
let u;
|
|
213
|
+
try { u = new URL(cfg.SERVE_PUBLIC_URL); } catch { /* reported below */ }
|
|
214
|
+
if (!u || !(u.protocol === 'https:' || ['localhost', '127.0.0.1'].includes(u.hostname)) || u.search || u.hash) errs.push('SERVE_PUBLIC_URL must be an https URL (no query), e.g. https://mcp.example.com.');
|
|
215
|
+
}
|
|
216
|
+
if (!['auto', 'tool', 'elicit'].includes(String(cfg.ASK_MODE))) errs.push('ASK_MODE must be auto, tool or elicit.');
|
|
217
|
+
if (!/^\d+$/.test(String(cfg.ELICIT_TIMEOUT_SECONDS)) || Number(cfg.ELICIT_TIMEOUT_SECONDS) < 10 || Number(cfg.ELICIT_TIMEOUT_SECONDS) > 600) errs.push('ELICIT_TIMEOUT_SECONDS must be 10-600.');
|
|
187
218
|
for (const k of ['RES_CPU_CRITICAL', 'RES_MEM_CRITICAL', 'RES_DISK_CRITICAL']) {
|
|
188
219
|
if (!/^\d+$/.test(String(cfg[k])) || Number(cfg[k]) < 1 || Number(cfg[k]) > 100) errs.push(`${k} must be a percentage, 1-100.`);
|
|
189
220
|
}
|
|
@@ -213,6 +244,16 @@ function shq(v) {
|
|
|
213
244
|
return `'${s}'`;
|
|
214
245
|
}
|
|
215
246
|
|
|
247
|
+
/** Set (or with null, remove) one KEY='value' line in secrets.env, mode 600. */
|
|
248
|
+
export function setSecret(file, key, value) {
|
|
249
|
+
const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter((l) => !l.startsWith(`${key}=`)) : [];
|
|
250
|
+
while (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
251
|
+
if (value != null) lines.push(`${key}='${value}'`);
|
|
252
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
253
|
+
fs.writeFileSync(file, lines.join('\n') + '\n', { mode: 0o600 });
|
|
254
|
+
fs.chmodSync(file, 0o600);
|
|
255
|
+
}
|
|
256
|
+
|
|
216
257
|
/** runtime.env: what the shell scripts and systemd units read. */
|
|
217
258
|
export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformId = 'linux' } = {}) {
|
|
218
259
|
const p = paths(env);
|
|
@@ -238,6 +279,8 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
|
|
|
238
279
|
HD_PLATFORM: platformId,
|
|
239
280
|
HD_AUTO_UPGRADE: cfg.AUTO_UPGRADE,
|
|
240
281
|
HD_AUTO_UPGRADE_HOURS: cfg.AUTO_UPGRADE_HOURS,
|
|
282
|
+
HD_WATCHDOG: cfg.RES_WATCHDOG || 'on',
|
|
283
|
+
...limitsMod.runtimeVars(cfg),
|
|
241
284
|
// Linux: the virtual display. macOS: the real screen, no DISPLAY.
|
|
242
285
|
...(platformId === 'linux' ? { DISPLAY: `:${cfg.DISPLAY_NUM}` } : {}),
|
|
243
286
|
// Services start with a bare PATH; keep the one the installer ran with, so
|
|
@@ -280,8 +323,19 @@ export const SETTABLE_KEYS = {
|
|
|
280
323
|
RES_CPU_CRITICAL: 'CPU busy % that counts as critical',
|
|
281
324
|
RES_MEM_CRITICAL: 'available RAM % at or below which the device is critical',
|
|
282
325
|
RES_DISK_CRITICAL: 'free disk % at or below which the device is critical',
|
|
326
|
+
ASK_MODE: 'how device tools ask the user: auto (AskUserQuestion in Remote Control sessions, a form locally), tool (always AskUserQuestion) or elicit (form when the client supports it)',
|
|
327
|
+
RES_RESERVE_MEM: 'RAM always kept free for the OS, Docker and other apps; heavy new work is refused below it (empty = max(1 GB, 12%); e.g. 1536, 1.5G, 15%)',
|
|
328
|
+
RES_HARNESS_MEM_MAX: 'RAM for everything harness-device runs together (sessions, processes, browser); over it the largest registered process is stopped (empty = 60%)',
|
|
329
|
+
RES_PROC_MEM_MAX: 'RAM per registered process (empty = 25%; needs install to apply on Linux)',
|
|
330
|
+
RES_PROC_CPU_MAX: 'CPU % per registered process, 100 = one core (empty = half the cores; needs install to apply on Linux)',
|
|
331
|
+
RES_BROWSER_MEM_MAX: 'RAM for the device Chromium (empty = min(1.5 GB, 20%); needs install to apply on Linux)',
|
|
332
|
+
RES_CONTAINER_MEM_DEFAULT: 'memory limit suggested for Docker containers that have none (empty = 512M)',
|
|
333
|
+
MAX_SESSIONS: 'most agent sessions at once (empty = number of cores, at least 2)',
|
|
334
|
+
MAX_PROCS: 'most registered processes at once (empty = 6)',
|
|
335
|
+
RES_WATCHDOG: 'on = stop registered processes and the browser that stay over their limits (they restart), off = only report',
|
|
336
|
+
ELICIT_TIMEOUT_SECONDS: 'how long a form waits for an answer before the tool falls back to AskUserQuestion (10-600)',
|
|
283
337
|
};
|
|
284
|
-
const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS|AUTO_UPGRADE|RESOURCE_GUARD)/;
|
|
338
|
+
const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS|AUTO_UPGRADE|RESOURCE_GUARD|RES_PROC_|RES_BROWSER_|RES_WATCHDOG)/;
|
|
285
339
|
|
|
286
340
|
/** Validate and save one settable key; returns { key, value, needsInstall }. */
|
|
287
341
|
export function setConfigValue(key, value, env = process.env) {
|
package/src/container.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// HD_CONTAINER=1: `harness-device serve` as a Docker container (a Dokploy
|
|
2
|
+
// app). It sees the host's Docker (the mounted socket), RAM and CPU (/proc is
|
|
3
|
+
// the host's), and disk through a read-only mount of / at HD_HOST_ROOT. It
|
|
4
|
+
// has no tmux sessions, processes or browser, so only the tools that make
|
|
5
|
+
// sense there are served.
|
|
6
|
+
//
|
|
7
|
+
// Configuration comes from the environment (Dokploy's Environment tab),
|
|
8
|
+
// not config.env: DEVICE, SERVE_PUBLIC_URL, SERVE_PORT, SERVE_OWNER_PASSWORD,
|
|
9
|
+
// and the RES_* limits.
|
|
10
|
+
|
|
11
|
+
export const isContainer = (env = process.env) => env.HD_CONTAINER === '1';
|
|
12
|
+
|
|
13
|
+
/** Tools a container can actually do something with. */
|
|
14
|
+
export const CONTAINER_TOOLS = ['resources', 'docker_summary', 'docker_limit', 'disk_cleanup'];
|
|
15
|
+
|
|
16
|
+
const FROM_ENV = /^(DEVICE|SERVE_PUBLIC_URL|SERVE_PORT|RES_[A-Z_]+|RESOURCE_GUARD|ASK_MODE)$/;
|
|
17
|
+
|
|
18
|
+
/** The container's config: defaults + file, then the environment, with a fixed capability set. */
|
|
19
|
+
export function containerConfig(cfg, env = process.env) {
|
|
20
|
+
const out = { ...cfg };
|
|
21
|
+
for (const [k, v] of Object.entries(env)) if (FROM_ENV.test(k) && v !== undefined && v !== '') out[k] = v;
|
|
22
|
+
out.SERVE_HOST = env.SERVE_HOST || '0.0.0.0';
|
|
23
|
+
out.CAPABILITIES = 'shell,system,docker';
|
|
24
|
+
for (const k of Object.keys(out)) if (k.startsWith('PROJECT_')) delete out[k];
|
|
25
|
+
return out;
|
|
26
|
+
}
|