@dreamtree-org/harness-device 0.1.8 → 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 +11 -0
- package/package.json +2 -1
- package/src/capabilities.js +16 -1
- package/src/cli.js +34 -1
- package/src/config.js +5 -0
- package/src/mcp/server.js +9 -0
- package/src/platform/darwin.js +2 -1
- 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 +2 -0
- package/src/serve/scopes.js +1 -1
- package/templates/systemd/harness-pool.service +16 -0
package/README.md
CHANGED
|
@@ -193,6 +193,15 @@ Disk running out? `harness-device cleanup`, or the `disk_cleanup` tool, lists wh
|
|
|
193
193
|
3. Run `install`.
|
|
194
194
|
4. Add `https://mcp.example.com/mcp` to your MCP client.
|
|
195
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
|
+
|
|
196
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`.
|
|
197
206
|
|
|
198
207
|
## Commands
|
|
@@ -216,6 +225,7 @@ Disk running out? `harness-device cleanup`, or the `disk_cleanup` tool, lists wh
|
|
|
216
225
|
| `config get [KEY]`, `config set KEY=VALUE` | The settings a remote session may change (app ports, Dokploy tool filters, transcript days) |
|
|
217
226
|
| `mcp` | The harness-device MCP server (stdio) |
|
|
218
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` |
|
|
219
229
|
| `limits [--enforce]` | Safe maximums against current use; `--enforce` runs one watchdog pass |
|
|
220
230
|
| `cleanup [--apply] [item…]` | What can be freed safely, with sizes; `--apply` removes it |
|
|
221
231
|
| `fleet add <name> <user@host>`, `fleet status`, `fleet run <name> <args>` | Many devices from one machine, over ssh |
|
|
@@ -237,6 +247,7 @@ Pick them with `init --with`/`--without`, or edit `CAPABILITIES=` in `config.env
|
|
|
237
247
|
| `dokploy` | API only | API only | Dokploy MCP against your deployment (`DOKPLOY_URL` + `secrets set DOKPLOY_API_KEY`); nothing is installed |
|
|
238
248
|
| `graphify` | | | `@dreamtree-org/graphify` CLI; `graphify .` wires a project's graph MCP and hooks |
|
|
239
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` |
|
|
240
251
|
| `serve` | systemd unit | launchd agent | These tools over HTTP with OAuth (`harness-device serve`), for other MCP clients |
|
|
241
252
|
| `ollama` | ollama.com script | Homebrew (Intel: Ollama app) | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
|
|
242
253
|
|
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/src/capabilities.js
CHANGED
|
@@ -229,6 +229,21 @@ Deployments go through the user's Dokploy at ${cfg.DOKPLOY_URL || '(DOKPLOY_URL
|
|
|
229
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
230
|
},
|
|
231
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
|
+
|
|
232
247
|
ngrok: {
|
|
233
248
|
label: 'ngrok tunnels (off until `harness-device ngrok up`)',
|
|
234
249
|
system: ['ngrok'],
|
|
@@ -252,7 +267,7 @@ Ollama serves \`http://127.0.0.1:11434\` (OpenAI-compatible at \`/v1\`). Models:
|
|
|
252
267
|
},
|
|
253
268
|
};
|
|
254
269
|
|
|
255
|
-
export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'serve', 'ollama'];
|
|
270
|
+
export const ORDER = ['shell', 'system', 'display', 'browser', 'playwright', 'sqlite', 'docker', 'dokploy', 'graphify', 'ngrok', 'serve', 'pool', 'ollama'];
|
|
256
271
|
|
|
257
272
|
/** Resolve the enabled set: config list + required + dependencies, in a stable order. */
|
|
258
273
|
export function resolveCapabilities(ids) {
|
package/src/cli.js
CHANGED
|
@@ -53,6 +53,9 @@ ${color.bold('Device')}
|
|
|
53
53
|
serve password [--rotate] show (or create/rotate) the owner password the OAuth consent page asks for
|
|
54
54
|
serve clients | serve revoke <id> apps that connected, with their scopes; revoke one and all its tokens
|
|
55
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
|
|
56
59
|
limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
|
|
57
60
|
cleanup [--apply] [item...] [--json] what could be freed safely (caches, build cache, old reports/logs); --apply removes it
|
|
58
61
|
gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
|
|
@@ -74,7 +77,7 @@ Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).j
|
|
|
74
77
|
`;
|
|
75
78
|
|
|
76
79
|
const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart', 'enforce', 'quiet'];
|
|
77
|
-
const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
80
|
+
const VALUE_FLAGS = ['enroll', 'device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
|
|
78
81
|
|
|
79
82
|
// Commands whose tail is someone else's command line, kept verbatim:
|
|
80
83
|
// `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
|
|
@@ -276,6 +279,36 @@ export async function main(argv) {
|
|
|
276
279
|
return serveCli.run(ctx, sub, rest, f);
|
|
277
280
|
}
|
|
278
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
|
+
|
|
279
312
|
case 'cleanup': {
|
|
280
313
|
const ctx = loadContext(env);
|
|
281
314
|
const items = cleanup.plan(ctx);
|
package/src/config.js
CHANGED
|
@@ -29,6 +29,7 @@ export function paths(env = process.env) {
|
|
|
29
29
|
pkg: path.join(home, 'pkg'),
|
|
30
30
|
fleet: path.join(home, 'fleet.tsv'),
|
|
31
31
|
ngrokEnv: path.join(home, 'ngrok.env'),
|
|
32
|
+
pool: path.join(home, 'pool.env'),
|
|
32
33
|
state: path.join(home, 'state'),
|
|
33
34
|
logs: path.join(home, 'logs'),
|
|
34
35
|
profile: path.join(home, 'chromium-profile'),
|
|
@@ -94,6 +95,9 @@ export function defaults(env = process.env) {
|
|
|
94
95
|
SERVE_HOST: '127.0.0.1',
|
|
95
96
|
SERVE_PORT: '7700',
|
|
96
97
|
SERVE_PUBLIC_URL: '',
|
|
98
|
+
// Pool (capability "pool", harness-device join): what the pool hub may do
|
|
99
|
+
// here. Set on the machine only; the hub can never raise it.
|
|
100
|
+
POOL_SCOPES: 'device:read,device:operate',
|
|
97
101
|
};
|
|
98
102
|
}
|
|
99
103
|
|
|
@@ -206,6 +210,7 @@ export function validateConfig(cfg, env = process.env) {
|
|
|
206
210
|
if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
|
|
207
211
|
if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
|
|
208
212
|
errs.push(...limitsMod.validate(cfg));
|
|
213
|
+
if (cfg.POOL_SCOPES !== undefined && !/^device:(read|operate|admin)(,device:(read|operate|admin))*$/.test(String(cfg.POOL_SCOPES).replace(/\s/g, ''))) errs.push('POOL_SCOPES must be a comma-separated list of device:read, device:operate, device:admin.');
|
|
209
214
|
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
215
|
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
216
|
if (cfg.SERVE_PUBLIC_URL) {
|
package/src/mcp/server.js
CHANGED
|
@@ -91,6 +91,15 @@ export function buildServer(env = process.env, opts = {}) {
|
|
|
91
91
|
return text(`proc ${a.name} registered; window proc-${a.name}; logs: logs tool with target "proc-${a.name}"`);
|
|
92
92
|
});
|
|
93
93
|
|
|
94
|
+
tool('session_new', 'Start another persistent agent session (a new conversation that survives reboots) for a project on this device. Refused beyond MAX_SESSIONS or while the device is critical.',
|
|
95
|
+
{ project: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/).describe(`one of: ${base.projects.map((p) => p.name).join(', ') || '(no projects yet)'}`), ...FORCE },
|
|
96
|
+
async (c, a) => {
|
|
97
|
+
await guard(c, a, 'a new session');
|
|
98
|
+
const r = state.newSlot(c, a.project);
|
|
99
|
+
state.applyLayout(c);
|
|
100
|
+
return text(`${a.project} slot ${r.slot}: conversation ${r.id}, window ${state.windowName(a.project, r.slot)}. It shows up in Remote Control as a new session within a minute.`);
|
|
101
|
+
});
|
|
102
|
+
|
|
94
103
|
tool('proc_remove', 'Stop and unregister a long-running process (asks the user first).', { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), ...CONFIRM },
|
|
95
104
|
async (c, a, u) => {
|
|
96
105
|
await u.confirm(`Stop and unregister process "${a.name}"? It will no longer restart or come back after a reboot.`);
|
package/src/platform/darwin.js
CHANGED
|
@@ -54,7 +54,7 @@ function intervalSeconds(s) {
|
|
|
54
54
|
return m[2] && m[2].startsWith('m') ? n * 60 : m[2] === 'h' ? n * 3600 : n;
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
export const LAUNCHABLE = ['harness-tmux', 'harness-chromium', 'harness-ttyd', 'harness-heal', 'harness-ngrok', 'harness-serve'];
|
|
57
|
+
export const LAUNCHABLE = ['harness-tmux', 'harness-chromium', 'harness-ttyd', 'harness-heal', 'harness-ngrok', 'harness-serve', 'harness-pool'];
|
|
58
58
|
export const launcherName = (u) => `harness-device-${u.replace(/^harness-/, '')}`;
|
|
59
59
|
|
|
60
60
|
/** Named copies of hd-run (see jobs()), replaced atomically like every script. */
|
|
@@ -90,6 +90,7 @@ export function jobs(ctx, detect = true) {
|
|
|
90
90
|
'harness-heal': { args: [run('harness-heal'), b('hd-heal')], keepAlive: false, interval: intervalSeconds(c.HEAL_INTERVAL) },
|
|
91
91
|
'harness-ngrok': { args: [run('harness-ngrok'), b('hd-ngrok')] },
|
|
92
92
|
'harness-serve': { args: [run('harness-serve'), b('harness-device'), 'serve'] },
|
|
93
|
+
'harness-pool': { args: [run('harness-pool'), b('harness-device'), 'pool', 'link'] },
|
|
93
94
|
};
|
|
94
95
|
return (u) => {
|
|
95
96
|
const d = def[u];
|
package/src/pool/join.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// Joining a pool hub (HarnessPro), the RunnerPro way: the hub's one-time
|
|
2
|
+
// install command carries a one-time enroll secret; it is exchanged here for a
|
|
3
|
+
// signed device credential, kept in pool.env (mode 600). From then on the
|
|
4
|
+
// device only connects out (src/pool/link.js).
|
|
5
|
+
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import { capture } from '../util.js';
|
|
10
|
+
import { PKG } from '../util.js';
|
|
11
|
+
import { parseEnv } from '../config.js';
|
|
12
|
+
|
|
13
|
+
/** A stable id for this machine (not the hostname): a cloned disk can't take over another device's entry. */
|
|
14
|
+
export function machineId(platformId = process.platform, read = fs.readFileSync, run = capture) {
|
|
15
|
+
let raw = '';
|
|
16
|
+
if (platformId === 'linux') {
|
|
17
|
+
for (const f of ['/etc/machine-id', '/var/lib/dbus/machine-id']) { try { raw = read(f, 'utf8').trim(); if (raw) break; } catch { /* next */ } }
|
|
18
|
+
} else if (platformId === 'darwin') {
|
|
19
|
+
raw = (run('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']).match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/) || [])[1] || '';
|
|
20
|
+
}
|
|
21
|
+
return crypto.createHash('sha256').update(raw || `${os.hostname()}|${os.userInfo().username}`).digest('hex');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function readPool(file) {
|
|
25
|
+
try { return parseEnv(fs.readFileSync(file, 'utf8')); } catch { return {}; }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function writePool(file, values) {
|
|
29
|
+
if (!values) { fs.rmSync(file, { force: true }); return; }
|
|
30
|
+
const body = Object.entries(values).map(([k, v]) => {
|
|
31
|
+
if (/['\n]/.test(String(v))) throw new Error(`Bad ${k} from the hub`);
|
|
32
|
+
return `${k}='${v}'`;
|
|
33
|
+
}).join('\n');
|
|
34
|
+
fs.writeFileSync(file, body + '\n', { mode: 0o600 });
|
|
35
|
+
fs.chmodSync(file, 0o600);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function normalizeHub(url) {
|
|
39
|
+
let u;
|
|
40
|
+
try { u = new URL(url); } catch { throw new Error(`Not a URL: ${url}`); }
|
|
41
|
+
if (u.protocol !== 'https:' && !['localhost', '127.0.0.1'].includes(u.hostname)) throw new Error('The pool hub must be https (http only for localhost)');
|
|
42
|
+
return u.origin;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Exchange the enroll secret for a credential; returns what was saved (without the credential). */
|
|
46
|
+
export async function join(ctx, hubUrl, enroll, { fetchImpl = fetch } = {}) {
|
|
47
|
+
if (!/^[A-Za-z0-9_-]{20,128}$/.test(enroll || '')) throw new Error('usage: harness-device join <hub-url> --enroll <secret from the hub\'s install command>');
|
|
48
|
+
const hub = normalizeHub(hubUrl);
|
|
49
|
+
const prev = readPool(ctx.paths.pool);
|
|
50
|
+
const res = await fetchImpl(`${hub}/device/v1/enroll`, {
|
|
51
|
+
method: 'POST',
|
|
52
|
+
headers: { 'content-type': 'application/json' },
|
|
53
|
+
body: JSON.stringify({
|
|
54
|
+
enroll,
|
|
55
|
+
device: ctx.cfg.DEVICE,
|
|
56
|
+
machine: machineId(ctx.platform.id),
|
|
57
|
+
os: ctx.platform.id,
|
|
58
|
+
arch: process.arch,
|
|
59
|
+
version: PKG.version,
|
|
60
|
+
caps: ctx.caps.map((c) => c.id),
|
|
61
|
+
// Re-joining the same hub keeps this device's entry (the hub checks the machine id too).
|
|
62
|
+
previous: prev.POOL_URL === hub ? prev.POOL_CREDENTIAL || '' : '',
|
|
63
|
+
}),
|
|
64
|
+
signal: AbortSignal.timeout(20000),
|
|
65
|
+
});
|
|
66
|
+
const body = await res.json().catch(() => ({}));
|
|
67
|
+
if (!res.ok || !body.credential) throw new Error(`The hub refused to enroll this device: ${body.error || `HTTP ${res.status}`}`);
|
|
68
|
+
const saved = { POOL_URL: hub, POOL_CREDENTIAL: body.credential, POOL_DEVICE_ID: body.deviceId || '', POOL_ACCOUNT: body.account || '' };
|
|
69
|
+
writePool(ctx.paths.pool, saved);
|
|
70
|
+
return { hub, deviceId: saved.POOL_DEVICE_ID, account: saved.POOL_ACCOUNT };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Tell the hub (best effort) and forget the credential. */
|
|
74
|
+
export async function leave(ctx, { fetchImpl = fetch } = {}) {
|
|
75
|
+
const p = readPool(ctx.paths.pool);
|
|
76
|
+
if (!p.POOL_URL) return { left: false };
|
|
77
|
+
try {
|
|
78
|
+
await fetchImpl(`${p.POOL_URL}/device/v1/leave`, { method: 'POST', headers: { authorization: `Device ${p.POOL_CREDENTIAL}` }, signal: AbortSignal.timeout(10000) });
|
|
79
|
+
} catch { /* the hub forgets it when the owner removes it there */ }
|
|
80
|
+
writePool(ctx.paths.pool, null);
|
|
81
|
+
return { left: true, hub: p.POOL_URL };
|
|
82
|
+
}
|
package/src/pool/link.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// The `harness-pool` service: one outbound WebSocket to the pool hub.
|
|
2
|
+
//
|
|
3
|
+
// device → hub hello { version, device, caps, tools: [{name, description, inputSchema}] }
|
|
4
|
+
// beat { resources, limits, max, counts, secretsVer, configVer } every 15s
|
|
5
|
+
// result { id, result } per call
|
|
6
|
+
// synced { kind, report } after secrets/config
|
|
7
|
+
// hub → device call { id, tool, args }
|
|
8
|
+
// secrets { ver, values } config { ver, values }
|
|
9
|
+
// disconnect
|
|
10
|
+
//
|
|
11
|
+
// Calls run through this device's own MCP server (buildServer) over an
|
|
12
|
+
// in-memory transport, so every local rule applies unchanged: POOL_SCOPES
|
|
13
|
+
// (set on the machine, never by the hub), confirmations, the resource gate,
|
|
14
|
+
// the safe maximums.
|
|
15
|
+
|
|
16
|
+
import WebSocket from 'ws';
|
|
17
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
18
|
+
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
|
|
19
|
+
import { loadContext } from '../context.js';
|
|
20
|
+
import { buildServer } from '../mcp/server.js';
|
|
21
|
+
import { allowFor } from '../serve/scopes.js';
|
|
22
|
+
import * as resources from '../resources.js';
|
|
23
|
+
import * as limits from '../limits.js';
|
|
24
|
+
import * as state from '../state.js';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { PKG } from '../util.js';
|
|
27
|
+
import { readPool, writePool } from './join.js';
|
|
28
|
+
import { applySecrets, applyConfig, versions } from './sync.js';
|
|
29
|
+
|
|
30
|
+
const BEAT_MS = 15000;
|
|
31
|
+
export const REVOKED = 4401;
|
|
32
|
+
|
|
33
|
+
export const poolScopes = (cfg) => String(cfg.POOL_SCOPES || 'device:read,device:operate').split(',').map((s) => s.trim()).filter(Boolean);
|
|
34
|
+
|
|
35
|
+
/** An MCP client wired to this device's own tools, limited to POOL_SCOPES. */
|
|
36
|
+
export async function localTools(env) {
|
|
37
|
+
const ctx = loadContext(env);
|
|
38
|
+
const server = buildServer(env, { transport: 'http', allow: allowFor(poolScopes(ctx.cfg)) });
|
|
39
|
+
const [a, b] = InMemoryTransport.createLinkedPair();
|
|
40
|
+
await server.connect(a);
|
|
41
|
+
const client = new Client({ name: 'harness-pool', version: PKG.version });
|
|
42
|
+
await client.connect(b);
|
|
43
|
+
return { client, close: () => client.close() };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function beat(env) {
|
|
47
|
+
const ctx = loadContext(env);
|
|
48
|
+
const s = await resources.sample(ctx, { quick: true });
|
|
49
|
+
let gs = [];
|
|
50
|
+
try { gs = limits.groups(ctx); } catch { /* no tmux yet */ }
|
|
51
|
+
const l = limits.limits(ctx.cfg);
|
|
52
|
+
return {
|
|
53
|
+
t: 'beat',
|
|
54
|
+
resources: { level: s.level, reasons: s.reasons, cpu: s.cpu, memory: s.memory, disk: s.disk },
|
|
55
|
+
limits: limits.report(ctx, gs),
|
|
56
|
+
max: { reserveMem: l.reserveMem, harnessMem: l.harnessMem, procMem: l.procMem, procCpu: l.procCpu, maxSessions: l.maxSessions, maxProcs: l.maxProcs, cores: l.cores, totalMem: l.totalMem },
|
|
57
|
+
counts: { sessions: gs.filter((g) => g.kind === 'session').length, procs: state.listProcs(ctx).length, harnessRss: gs.reduce((a, g) => a + g.rss, 0) },
|
|
58
|
+
caps: ctx.caps.map((c) => c.id),
|
|
59
|
+
...versions(ctx),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Handle one message from the hub. `send` replies; returns 'stop' when the
|
|
65
|
+
* device was disconnected by the hub.
|
|
66
|
+
*/
|
|
67
|
+
export async function handle(env, tools, msg, send) {
|
|
68
|
+
const ctx = loadContext(env);
|
|
69
|
+
switch (msg.t) {
|
|
70
|
+
case 'call': {
|
|
71
|
+
let result;
|
|
72
|
+
try {
|
|
73
|
+
result = await tools.client.callTool({ name: String(msg.tool), arguments: msg.args || {} }, undefined, { timeout: Math.min(Number(msg.timeoutMs) || 120000, 2 * 3600 * 1000) });
|
|
74
|
+
} catch (e) {
|
|
75
|
+
result = { isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] };
|
|
76
|
+
}
|
|
77
|
+
send({ t: 'result', id: msg.id, result });
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
case 'secrets': {
|
|
81
|
+
const report = applySecrets(ctx, String(msg.ver || ''), msg.values || {});
|
|
82
|
+
state.event(ctx, `pool: secrets synced (set ${report.set.length}, removed ${report.removed.length}${report.skipped.length ? `, skipped ${report.skipped.map((x) => x.name).join(', ')}` : ''})`);
|
|
83
|
+
send({ t: 'synced', kind: 'secrets', report });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
case 'config': {
|
|
87
|
+
const report = applyConfig(ctx, String(msg.ver || ''), msg.values || {}, env);
|
|
88
|
+
// Kernel-held limits (systemd units) take a graceful install; it runs in the background.
|
|
89
|
+
let installing = false;
|
|
90
|
+
if (report.needsInstall && !msg.noInstall) {
|
|
91
|
+
try {
|
|
92
|
+
ctx.platform.spawnDetached(ctx, 'pool-install', [path.join(ctx.paths.bin, 'harness-device'), 'install', '--graceful', '--skip-system'], path.join(ctx.paths.logs, 'pool-install.log'));
|
|
93
|
+
installing = true;
|
|
94
|
+
} catch { /* reported below */ }
|
|
95
|
+
}
|
|
96
|
+
report.installing = installing;
|
|
97
|
+
state.event(ctx, `pool: settings synced (set ${report.set.join(', ') || 'none'}${report.reset.length ? `; back to default ${report.reset.join(', ')}` : ''})${report.needsInstall ? (installing ? '; applying the rest with a graceful install' : '; run harness-device install to apply all of them') : ''}`);
|
|
98
|
+
send({ t: 'synced', kind: 'config', report });
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
case 'disconnect': {
|
|
102
|
+
writePool(ctx.paths.pool, null);
|
|
103
|
+
state.event(ctx, 'pool: disconnected by the hub; credential removed');
|
|
104
|
+
return 'stop';
|
|
105
|
+
}
|
|
106
|
+
default:
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Run the link until stopped: reconnects with backoff, stops for good when revoked or disconnected. */
|
|
111
|
+
export async function runLink(env = process.env, { log = (m) => console.error(`[pool] ${m}`) } = {}) {
|
|
112
|
+
let delay = 1000;
|
|
113
|
+
for (;;) {
|
|
114
|
+
const p = readPool(loadContext(env).paths.pool);
|
|
115
|
+
if (!p.POOL_URL || !p.POOL_CREDENTIAL) {
|
|
116
|
+
log('not joined to a pool (harness-device join); checking again in 5 minutes');
|
|
117
|
+
await new Promise((r) => setTimeout(r, 300000));
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const outcome = await connectOnce(env, p, log);
|
|
121
|
+
if (outcome === 'stop') { log('disconnected by the hub; waiting to be joined again'); delay = 1000; continue; }
|
|
122
|
+
if (outcome === 'revoked') { log('the hub revoked this device; join again to reconnect'); await new Promise((r) => setTimeout(r, 600000)); continue; }
|
|
123
|
+
if (outcome === 'ok') delay = 1000;
|
|
124
|
+
const wait = Math.round(delay * (0.5 + Math.random()));
|
|
125
|
+
log(`reconnecting in ${Math.round(wait / 1000)}s`);
|
|
126
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
127
|
+
delay = Math.min(delay * 2, 60000);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** One connection. Resolves 'ok' (was connected, then dropped), 'failed', 'revoked' or 'stop'. */
|
|
132
|
+
export function connectOnce(env, p, log = () => {}) {
|
|
133
|
+
return new Promise((resolve) => {
|
|
134
|
+
const url = p.POOL_URL.replace(/^http/, 'ws') + '/device/v1/link';
|
|
135
|
+
const ws = new WebSocket(url, { headers: { authorization: `Device ${p.POOL_CREDENTIAL}` }, handshakeTimeout: 15000, maxPayload: 8 * 1024 * 1024 });
|
|
136
|
+
let tools;
|
|
137
|
+
let timer;
|
|
138
|
+
let connected = false;
|
|
139
|
+
let stopped = false;
|
|
140
|
+
const send = (m) => { if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(m)); };
|
|
141
|
+
const finish = (how) => { clearInterval(timer); if (tools) tools.close().catch(() => {}); resolve(how); };
|
|
142
|
+
ws.on('unexpected-response', (_req, res) => { log(`hub refused the link: HTTP ${res.statusCode}`); finish(res.statusCode === 401 || res.statusCode === 403 ? 'revoked' : 'failed'); });
|
|
143
|
+
ws.on('error', (e) => { log(`link error: ${e.message}`); });
|
|
144
|
+
ws.on('open', async () => {
|
|
145
|
+
connected = true;
|
|
146
|
+
log(`connected to ${p.POOL_URL}`);
|
|
147
|
+
try {
|
|
148
|
+
tools = await localTools(env);
|
|
149
|
+
const list = (await tools.client.listTools()).tools.map((x) => ({ name: x.name, description: x.description, inputSchema: x.inputSchema }));
|
|
150
|
+
const ctx = loadContext(env);
|
|
151
|
+
send({ t: 'hello', version: PKG.version, device: ctx.cfg.DEVICE, caps: ctx.caps.map((c) => c.id), scopes: poolScopes(ctx.cfg), tools: list });
|
|
152
|
+
send(await beat(env));
|
|
153
|
+
timer = setInterval(() => { beat(env).then(send).catch((e) => log(`heartbeat failed: ${e.message}`)); }, BEAT_MS);
|
|
154
|
+
} catch (e) {
|
|
155
|
+
log(`could not start the device tools: ${e.message}`);
|
|
156
|
+
ws.close();
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
ws.on('message', async (data) => {
|
|
160
|
+
let msg;
|
|
161
|
+
try { msg = JSON.parse(String(data)); } catch { return; }
|
|
162
|
+
if (!tools) return;
|
|
163
|
+
try {
|
|
164
|
+
if ((await handle(env, tools, msg, send)) === 'stop') { stopped = true; ws.close(1000); }
|
|
165
|
+
} catch (e) { log(`handling ${msg.t} failed: ${e.message}`); }
|
|
166
|
+
});
|
|
167
|
+
ws.on('close', (code) => finish(stopped ? 'stop' : code === REVOKED ? 'revoked' : connected ? 'ok' : 'failed'));
|
|
168
|
+
});
|
|
169
|
+
}
|
package/src/pool/sync.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// What the pool hub may change on this device: pool-managed secrets and the
|
|
2
|
+
// safe-maximum settings. Local values always win: a secret the owner set on
|
|
3
|
+
// the machine is never overwritten or removed, and only the keys the pool set
|
|
4
|
+
// are ever taken away again.
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { readSecrets } from '../context.js';
|
|
9
|
+
import { setSecret, setConfigValue, SETTABLE_KEYS, defaults } from '../config.js';
|
|
10
|
+
|
|
11
|
+
/** Names the pool may never set: they would break Remote Control, the server login, or the link itself. */
|
|
12
|
+
const DENY = /^(ANTHROPIC_|CLAUDE_CODE_USE_|SERVE_OWNER_PASSWORD$|POOL_|PATH$|HOME$|LD_|NODE_OPTIONS$|HARNESS_DEVICE_HOME$|HD_)/;
|
|
13
|
+
const NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
14
|
+
const VALUE = /^[^'\n\r]{1,4096}$/;
|
|
15
|
+
|
|
16
|
+
/** Settings the pool may manage (all of them also settable from a session, so validated the same way). */
|
|
17
|
+
export const POOL_CONFIG = /^(RES_[A-Z_]+|MAX_SESSIONS|MAX_PROCS|ASK_MODE|ELICIT_TIMEOUT_SECONDS)$/;
|
|
18
|
+
|
|
19
|
+
const file = (ctx, name) => path.join(ctx.paths.state, name);
|
|
20
|
+
const read = (f, d) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return d; } };
|
|
21
|
+
const write = (f, v) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify(v), { mode: 0o600 }); };
|
|
22
|
+
|
|
23
|
+
export function versions(ctx) {
|
|
24
|
+
return { secretsVer: read(file(ctx, 'pool-secrets.json'), {}).ver || '', configVer: read(file(ctx, 'pool-config.json'), {}).ver || '' };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Make the pool-managed secrets equal `values` ({NAME: value}).
|
|
29
|
+
* Returns { set, removed, skipped: [{name, why}] } — names only, never values.
|
|
30
|
+
*/
|
|
31
|
+
export function applySecrets(ctx, ver, values = {}) {
|
|
32
|
+
const f = file(ctx, 'pool-secrets.json');
|
|
33
|
+
const owned = new Set(read(f, {}).keys || []);
|
|
34
|
+
const local = readSecrets(ctx.paths.secrets);
|
|
35
|
+
const out = { set: [], removed: [], skipped: [] };
|
|
36
|
+
const keep = new Set();
|
|
37
|
+
for (const [name, value] of Object.entries(values)) {
|
|
38
|
+
if (!NAME.test(name) || DENY.test(name)) { out.skipped.push({ name, why: 'name not allowed' }); continue; }
|
|
39
|
+
if (typeof value !== 'string' || !VALUE.test(value)) { out.skipped.push({ name, why: 'value not allowed (quote, newline or too long)' }); continue; }
|
|
40
|
+
if (name in local && !owned.has(name)) { out.skipped.push({ name, why: 'set locally on this device; the local value wins' }); continue; }
|
|
41
|
+
if (local[name] !== value) setSecret(ctx.paths.secrets, name, value);
|
|
42
|
+
keep.add(name);
|
|
43
|
+
out.set.push(name);
|
|
44
|
+
}
|
|
45
|
+
for (const name of owned) {
|
|
46
|
+
if (!keep.has(name)) { setSecret(ctx.paths.secrets, name, null); out.removed.push(name); }
|
|
47
|
+
}
|
|
48
|
+
write(f, { ver, keys: [...keep] });
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Make the pool-managed settings equal `values`, through the same validation
|
|
54
|
+
* as config_set. A setting the pool set before and no longer sends goes back
|
|
55
|
+
* to this device's default. Returns { set, reset, skipped, needsInstall }.
|
|
56
|
+
*/
|
|
57
|
+
export function applyConfig(ctx, ver, values = {}, env = ctx.env) {
|
|
58
|
+
const f = file(ctx, 'pool-config.json');
|
|
59
|
+
const owned = new Set(read(f, {}).keys || []);
|
|
60
|
+
const out = { set: [], reset: [], skipped: [], needsInstall: false };
|
|
61
|
+
const keep = new Set();
|
|
62
|
+
for (const [key, value] of Object.entries(values)) {
|
|
63
|
+
if (!POOL_CONFIG.test(key) || !(key in SETTABLE_KEYS)) { out.skipped.push({ key, why: 'not a pool setting' }); continue; }
|
|
64
|
+
try {
|
|
65
|
+
const r = setConfigValue(key, String(value ?? ''), env);
|
|
66
|
+
out.set.push(key);
|
|
67
|
+
keep.add(key);
|
|
68
|
+
if (r.needsInstall) out.needsInstall = true;
|
|
69
|
+
} catch (e) {
|
|
70
|
+
out.skipped.push({ key, why: e.message });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
const base = defaults(env);
|
|
74
|
+
for (const key of owned) {
|
|
75
|
+
if (keep.has(key)) continue;
|
|
76
|
+
try {
|
|
77
|
+
const r = setConfigValue(key, String(base[key] ?? ''), env);
|
|
78
|
+
out.reset.push(key);
|
|
79
|
+
if (r.needsInstall) out.needsInstall = true;
|
|
80
|
+
} catch (e) { out.skipped.push({ key, why: e.message }); }
|
|
81
|
+
}
|
|
82
|
+
write(f, { ver, keys: [...keep] });
|
|
83
|
+
return out;
|
|
84
|
+
}
|
package/src/providers/claude.js
CHANGED
|
@@ -192,6 +192,8 @@ export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-d
|
|
|
192
192
|
'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)',
|
|
193
193
|
// The serve owner password, and approving/revoking apps, are the owner's.
|
|
194
194
|
'Bash(harness-device serve:*)',
|
|
195
|
+
// Joining or leaving a pool, and what the pool may do here, are the owner's.
|
|
196
|
+
'Bash(harness-device join:*)', 'Bash(harness-device leave:*)', 'Bash(harness-device pool:*)',
|
|
195
197
|
// Stopping ends every session and none could start the device again; restart goes through device_restart.
|
|
196
198
|
'Bash(harness-device stop:*)', 'Bash(harness-device start:*)', 'Bash(harness-device restart)', 'Bash(harness-device restart --:*)'];
|
|
197
199
|
|
package/src/serve/scopes.js
CHANGED
|
@@ -12,7 +12,7 @@ const ORDER = ['device:read', 'device:operate', 'device:admin'];
|
|
|
12
12
|
|
|
13
13
|
const TOOLS = {
|
|
14
14
|
'device:read': ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs', 'resources', 'screenshot', 'docker_summary', 'ngrok_status', 'config_get'],
|
|
15
|
-
'device:operate': ['proc_add', 'proc_remove', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit'],
|
|
15
|
+
'device:operate': ['proc_add', 'proc_remove', 'session_new', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit'],
|
|
16
16
|
};
|
|
17
17
|
|
|
18
18
|
/** Granted scopes with everything they include. */
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
[Unit]
|
|
2
|
+
Description=harness-device: link to the HarnessPro pool hub (outbound only)
|
|
3
|
+
After=network-online.target harness-tmux.service
|
|
4
|
+
Wants=network-online.target
|
|
5
|
+
PartOf=harness.target
|
|
6
|
+
|
|
7
|
+
[Service]
|
|
8
|
+
EnvironmentFile={{HD_HOME}}/runtime.env
|
|
9
|
+
ExecStart={{HD_HOME}}/bin/harness-device pool link
|
|
10
|
+
Restart=always
|
|
11
|
+
RestartSec=10
|
|
12
|
+
MemoryHigh=200M
|
|
13
|
+
MemoryMax=256M
|
|
14
|
+
|
|
15
|
+
[Install]
|
|
16
|
+
WantedBy=harness.target
|