@dreamtree-org/harness-device 0.1.7 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -0
- package/package.json +2 -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 +34 -1
- package/src/cleanup.js +195 -0
- package/src/cli.js +88 -11
- package/src/config.js +60 -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 +79 -45
- package/src/platform/darwin.js +3 -1
- package/src/platform/linux.js +2 -0
- package/src/pool/join.js +82 -0
- package/src/pool/link.js +169 -0
- package/src/pool/sync.js +84 -0
- package/src/providers/claude.js +6 -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-pool.service +16 -0
- package/templates/systemd/harness-serve.service +16 -0
- package/templates/systemd/harness-tmux.service +4 -0
package/README.md
CHANGED
|
@@ -158,6 +158,52 @@ 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
|
+
### Join a pool (HarnessPro)
|
|
197
|
+
|
|
198
|
+
`harness-device join <hub> --enroll <secret>` adds this device to a HarnessPro pool. You don't type it yourself: the dashboard's **Connect a device** gives a one-time `curl … | bash` command that installs harness-device and runs it.
|
|
199
|
+
- **Connection:** the device keeps one outbound WebSocket to the hub (no open ports) and sends its resources and safe maximums every 15 seconds.
|
|
200
|
+
- **Work from the pool:** the hub routes MCP calls here and places new sessions and processes on the device with the most room.
|
|
201
|
+
- **What the pool may do:** `POOL_SCOPES` in config.env sets it (default `device:read,device:operate`). It's set on the machine only, and the hub can never raise it.
|
|
202
|
+
- **Shared secrets and settings from the hub:** they never overwrite a secret you set locally, and never names such as `ANTHROPIC_*` or `SERVE_OWNER_PASSWORD`.
|
|
203
|
+
- **Leaving:** `harness-device leave`, or Disconnect in the dashboard.
|
|
204
|
+
|
|
205
|
+
**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`.
|
|
206
|
+
|
|
161
207
|
## Commands
|
|
162
208
|
|
|
163
209
|
| Command | What it does |
|
|
@@ -178,6 +224,10 @@ New work from a session waits while CPU, RAM or disk is critical, and is refused
|
|
|
178
224
|
| `ngrok token`, `ngrok up [viewers\|apps\|all\|<tunnel>] [--port 8099]`, `ngrok down`, `ngrok status` | Public URLs, off until you turn them on |
|
|
179
225
|
| `config get [KEY]`, `config set KEY=VALUE` | The settings a remote session may change (app ports, Dokploy tool filters, transcript days) |
|
|
180
226
|
| `mcp` | The harness-device MCP server (stdio) |
|
|
227
|
+
| `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 |
|
|
228
|
+
| `join <hub> --enroll <secret>`, `leave`, `pool` | Join or leave a HarnessPro pool; `pool` shows the hub and `POOL_SCOPES` |
|
|
229
|
+
| `limits [--enforce]` | Safe maximums against current use; `--enforce` runs one watchdog pass |
|
|
230
|
+
| `cleanup [--apply] [item…]` | What can be freed safely, with sizes; `--apply` removes it |
|
|
181
231
|
| `fleet add <name> <user@host>`, `fleet status`, `fleet run <name> <args>` | Many devices from one machine, over ssh |
|
|
182
232
|
| `uninstall [--purge]` | Remove services and agent wiring (`--purge` also deletes state and config) |
|
|
183
233
|
|
|
@@ -197,6 +247,8 @@ Pick them with `init --with`/`--without`, or edit `CAPABILITIES=` in `config.env
|
|
|
197
247
|
| `dokploy` | API only | API only | Dokploy MCP against your deployment (`DOKPLOY_URL` + `secrets set DOKPLOY_API_KEY`); nothing is installed |
|
|
198
248
|
| `graphify` | | | `@dreamtree-org/graphify` CLI; `graphify .` wires a project's graph MCP and hooks |
|
|
199
249
|
| `ngrok` | apt repo | Homebrew (Intel: ngrok's official release, into `~/.local/bin`) | Tunnels you open; the agent may only read them |
|
|
250
|
+
| `pool` | systemd unit | launchd agent | Member of a HarnessPro pool: outbound link, calls routed here within `POOL_SCOPES` |
|
|
251
|
+
| `serve` | systemd unit | launchd agent | These tools over HTTP with OAuth (`harness-device serve`), for other MCP clients |
|
|
200
252
|
| `ollama` | ollama.com script | Homebrew (Intel: Ollama app) | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
|
|
201
253
|
|
|
202
254
|
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 +292,7 @@ harness-device fleet status # every device: sessions, failing slots, serv
|
|
|
240
292
|
- 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
293
|
- `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
294
|
- `docker` access is root-equivalent on Linux. Leave the `docker` capability off on a device you share.
|
|
295
|
+
- `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
296
|
|
|
244
297
|
## Troubleshooting
|
|
245
298
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dreamtree-org/harness-device",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Partha Preetham Krishna",
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
61
|
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
62
|
+
"ws": "^8.18.3",
|
|
62
63
|
"zod": "^4.4.3"
|
|
63
64
|
}
|
|
64
65
|
}
|
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,37 @@ 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
|
+
|
|
232
|
+
pool: {
|
|
233
|
+
label: 'Member of a HarnessPro pool (harness-device join): the hub routes MCP calls here and places new work by capacity, over an outbound connection',
|
|
234
|
+
units: { linux: ['harness-pool'], darwin: ['harness-pool'] },
|
|
235
|
+
checks: async (ctx) => {
|
|
236
|
+
const { readPool } = await import('./pool/join.js');
|
|
237
|
+
const p = readPool(ctx.paths.pool);
|
|
238
|
+
return [
|
|
239
|
+
{ name: 'joined to a pool hub', ok: !!p.POOL_CREDENTIAL, msg: p.POOL_URL || undefined, fix: 'run the install command from the HarnessPro dashboard (Connect a device)' },
|
|
240
|
+
{ name: `pool scopes: ${ctx.cfg.POOL_SCOPES}`, ok: true },
|
|
241
|
+
];
|
|
242
|
+
},
|
|
243
|
+
docs: (cfg) => `## Pool
|
|
244
|
+
This device is in a HarnessPro pool: the hub may call this device's tools (within POOL_SCOPES: ${cfg.POOL_SCOPES}) and place new sessions and processes here when it has the most room. Work that arrives from the pool follows the same rules as yours (confirmations, resource guard, safe maximums). Joining, leaving and POOL_SCOPES are the owner's, on the machine.`,
|
|
245
|
+
},
|
|
246
|
+
|
|
214
247
|
ngrok: {
|
|
215
248
|
label: 'ngrok tunnels (off until `harness-device ngrok up`)',
|
|
216
249
|
system: ['ngrok'],
|
|
@@ -234,7 +267,7 @@ Ollama serves \`http://127.0.0.1:11434\` (OpenAI-compatible at \`/v1\`). Models:
|
|
|
234
267
|
},
|
|
235
268
|
};
|
|
236
269
|
|
|
237
|
-
export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'ollama'];
|
|
270
|
+
export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'serve', 'pool', 'ollama'];
|
|
238
271
|
|
|
239
272
|
/** Resolve the enabled set: config list + required + dependencies, in a stable order. */
|
|
240
273
|
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,15 @@ ${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
|
+
join <hub-url> --enroll <secret> join a HarnessPro pool (the dashboard's install command runs this)
|
|
57
|
+
leave leave the pool and forget its credential
|
|
58
|
+
pool [status] pool hub, link state, POOL_SCOPES; \`pool link\` is the service
|
|
59
|
+
limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
|
|
60
|
+
cleanup [--apply] [item...] [--json] what could be freed safely (caches, build cache, old reports/logs); --apply removes it
|
|
50
61
|
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
51
62
|
stop [--now] [--timeout 120] graceful shutdown: waits for agent turns to finish, ends sessions and processes
|
|
52
63
|
cleanly, saves the browser; stays stopped (also after reboots) until start
|
|
@@ -65,8 +76,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
|
|
|
65
76
|
Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
|
|
66
77
|
`;
|
|
67
78
|
|
|
68
|
-
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart'];
|
|
69
|
-
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
79
|
+
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart', 'enforce', 'quiet'];
|
|
80
|
+
const VALUE_FLAGS = ['enroll', 'device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
70
81
|
|
|
71
82
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
72
83
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -127,12 +138,6 @@ function refreshProjects(ctx) {
|
|
|
127
138
|
state.applyLayout(ctx);
|
|
128
139
|
}
|
|
129
140
|
|
|
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
141
|
|
|
137
142
|
function printStatus(s) {
|
|
138
143
|
console.log(`${color.bold(s.device)} ${color.dim(`· ${s.provider} · ${s.serveMode} mode · ${s.capabilities.join(', ')}`)}`);
|
|
@@ -253,6 +258,72 @@ export async function main(argv) {
|
|
|
253
258
|
return f.json ? console.log(JSON.stringify(s, null, 2)) : console.log(resources.summary(s) + (s.reasons.length ? `\n ${s.reasons.join('\n ')}` : ''));
|
|
254
259
|
}
|
|
255
260
|
|
|
261
|
+
case 'limits': {
|
|
262
|
+
const ctx = loadContext(env);
|
|
263
|
+
if (f.enforce) {
|
|
264
|
+
const r = await limits.enforce(ctx);
|
|
265
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
266
|
+
for (const a of r.actions) log.warn(`stopped ${a.name}: ${a.reason}`);
|
|
267
|
+
if (!f.quiet && !r.actions.length) log.ok('all within limits');
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
const r = limits.report(ctx);
|
|
271
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
272
|
+
for (const [k, v] of Object.entries(r)) console.log(`${k.padEnd(12)} ${Array.isArray(v) ? v.join(', ') : v}`);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
case 'serve': {
|
|
277
|
+
const ctx = loadContext(env);
|
|
278
|
+
const serveCli = await import('./serve/cli.js');
|
|
279
|
+
return serveCli.run(ctx, sub, rest, f);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
case 'join':
|
|
283
|
+
case 'leave':
|
|
284
|
+
case 'pool': {
|
|
285
|
+
const ctx = loadContext(env);
|
|
286
|
+
const pj = await import('./pool/join.js');
|
|
287
|
+
if (cmd === 'pool' && sub === 'link') return (await import('./pool/link.js')).runLink(env);
|
|
288
|
+
if (cmd === 'pool') {
|
|
289
|
+
const p = pj.readPool(ctx.paths.pool);
|
|
290
|
+
console.log(p.POOL_URL ? `hub ${p.POOL_URL} · device ${p.POOL_DEVICE_ID || '?'} · account ${p.POOL_ACCOUNT || '?'}` : 'not in a pool (join with the install command from the HarnessPro dashboard)');
|
|
291
|
+
return console.log(`POOL_SCOPES ${ctx.cfg.POOL_SCOPES} (what the pool may do here; change it in config.env, then harness-device install)`);
|
|
292
|
+
}
|
|
293
|
+
const { cfg } = loadConfig(env);
|
|
294
|
+
const caps = new Set(String(cfg.CAPABILITIES).split(',').map((s) => s.trim()).filter(Boolean));
|
|
295
|
+
if (cmd === 'join') {
|
|
296
|
+
if (!ctx.exists) throw new Error('Set this device up first: harness-device init');
|
|
297
|
+
const r = await pj.join(ctx, sub, f.enroll);
|
|
298
|
+
caps.add('pool');
|
|
299
|
+
saveConfig({ ...cfg, CAPABILITIES: [...caps].join(',') }, env);
|
|
300
|
+
log.ok(`joined ${r.hub}${r.account ? ` (${r.account})` : ''} as device ${r.deviceId}. The pool may use: ${ctx.cfg.POOL_SCOPES}.`);
|
|
301
|
+
} else {
|
|
302
|
+
const r = await pj.leave(ctx);
|
|
303
|
+
caps.delete('pool');
|
|
304
|
+
saveConfig({ ...cfg, CAPABILITIES: [...caps].join(',') }, env);
|
|
305
|
+
log.ok(r.left ? `left ${r.hub}` : 'not in a pool');
|
|
306
|
+
}
|
|
307
|
+
// Only the pool service changes: no system packages (no sudo prompt, which
|
|
308
|
+
// the hub's `curl | bash` install command could not answer).
|
|
309
|
+
return install(loadContext(env), { skipSystem: true, graceful: true });
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
case 'cleanup': {
|
|
313
|
+
const ctx = loadContext(env);
|
|
314
|
+
const items = cleanup.plan(ctx);
|
|
315
|
+
const ids = [sub, ...rest].filter(Boolean);
|
|
316
|
+
const r = f.apply ? cleanup.apply(ctx, ids, items) : cleanup.describe(items);
|
|
317
|
+
if (f.json) return console.log(JSON.stringify(r, null, 2));
|
|
318
|
+
if (f.apply) {
|
|
319
|
+
state.event(ctx, `cleanup freed ${r.freed}: ${r.done.map((x) => x.id).join(', ')}`);
|
|
320
|
+
for (const x of r.done) (x.ok ? log.ok : log.warn)(`${x.id}${x.ok ? '' : `: ${x.error}`}`);
|
|
321
|
+
return log.ok(`freed ${r.freed}`);
|
|
322
|
+
}
|
|
323
|
+
for (const i of r.items) console.log(`${i.size.padStart(9)} ${i.id}\n ${color.dim(i.what)}`);
|
|
324
|
+
return console.log(`\n${r.total} can be freed. Run: harness-device cleanup --apply [item...]`);
|
|
325
|
+
}
|
|
326
|
+
|
|
256
327
|
case 'gate': {
|
|
257
328
|
const ctx = loadContext(env);
|
|
258
329
|
if (f.hook) return gateHook(ctx);
|
|
@@ -529,12 +600,18 @@ async function gateHook(ctx) {
|
|
|
529
600
|
const cmd = (input.tool_input && input.tool_input.command) || '';
|
|
530
601
|
if (resources.isLightCommand(cmd)) return;
|
|
531
602
|
const force = /(^|\s)HD_FORCE=1(\s|$)/.test(cmd);
|
|
603
|
+
// A remote user sees a silent wait as a hung session: refuse at once and
|
|
604
|
+
// let the agent ask them what to do instead.
|
|
605
|
+
const remote = ctx.env.HD_REMOTE_CONTROL === '1';
|
|
532
606
|
try {
|
|
533
|
-
await resources.gate(ctx, { force, quick: true, waitSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 0, 540), what: 'this command' });
|
|
607
|
+
await resources.gate(ctx, { force, quick: true, waitSeconds: remote ? 0 : Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 0, 540), what: 'this command' });
|
|
534
608
|
} catch (e) {
|
|
535
609
|
if (!(e instanceof resources.ResourceDenied)) return;
|
|
610
|
+
const next = remote
|
|
611
|
+
? ' 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.'
|
|
612
|
+
: ' Check with: harness-device resources.';
|
|
536
613
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny',
|
|
537
|
-
permissionDecisionReason: `${e.message}
|
|
614
|
+
permissionDecisionReason: `${e.message}${next}` } }));
|
|
538
615
|
}
|
|
539
616
|
} catch { /* fail open */ }
|
|
540
617
|
}
|