@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/src/mcp/server.js CHANGED
@@ -14,54 +14,54 @@ import { PKG, sendChildOutputToStderr, capture } from '../util.js';
14
14
  import { SETTABLE_KEYS, setConfigValue } from '../config.js';
15
15
  import * as resources from '../resources.js';
16
16
  import * as upgrader from '../upgrade.js';
17
+ import * as cleanup from '../cleanup.js';
18
+ import * as limits from '../limits.js';
19
+ import { Cancelled, NeedsUser, interaction } from './interact.js';
17
20
 
18
21
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
19
22
  const fail = (e) => ({ isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] });
20
23
 
21
24
  const has = (ctx, id) => ctx.caps.some((c) => c.id === id);
22
25
 
26
+ /** Present on every tool that confirms first; see ./interact.js. */
27
+ const CONFIRM = { confirm_token: z.string().max(64).optional().describe('the token from this tool\'s previous reply, after the user said Go ahead through AskUserQuestion') };
28
+
23
29
  /** `force`: skip waiting for a critical device (and be refused while it stays critical). */
24
30
  const FORCE = { force: z.boolean().optional().describe('skip waiting when the device is critical; refused while critical') };
25
31
 
26
32
  /** Resource guard for new work: waits while CPU/RAM/disk is critical, refuses if it stays so. */
27
33
  async function guard(c, a, what) {
28
34
  await resources.gate(c, { force: !!a.force, what, waitSeconds: Math.min(Number(c.cfg.RES_WAIT_SECONDS) || 0, 240) });
35
+ // The RAM reserve is for the OS, Docker and other apps: heavy new work never eats into it.
36
+ const m = resources.memory();
37
+ if (String(c.cfg.RESOURCE_GUARD || 'on') !== 'off' && limits.underReserve(c.cfg, m.available)) {
38
+ const s = await resources.sample(c, { quick: true });
39
+ throw new resources.ResourceDenied(`Refused ${what}: only ${limits.humanMem(m.available)} of RAM is available, under the ${limits.humanMem(limits.limits(c.cfg).reserveMem)} kept free for the OS and other apps (RES_RESERVE_MEM). Free memory first (stop a process, close the browser's tabs) or ask the user.`, s);
40
+ }
29
41
  }
30
42
 
31
- /** Thrown when the user declines or cancels a form; reported as a plain result, not a failure. */
32
- class Cancelled extends Error {}
33
-
34
43
  /**
35
- * Ask the user for missing details with an MCP elicitation form (rendered by
36
- * the client: a dialog or card the remote user fills in). Without client
37
- * support it fails with the field names, so the agent asks with its own UI.
44
+ * opts.transport: 'stdio' (a local child of the agent) or 'http' (`serve`);
45
+ * it decides how the tools ask the user (see ./interact.js).
46
+ * opts.allow(name): register only the tools it accepts (`serve` scopes).
38
47
  */
39
- async function ask(server, message, properties, required = Object.keys(properties)) {
40
- if (!server.server.getClientCapabilities()?.elicitation) {
41
- throw new Error(`Missing: ${Object.keys(properties).join(', ')}. Ask the user (with your interactive question tool) and call again with them.`);
42
- }
43
- const r = await server.server.elicitInput({ mode: 'form', message, requestedSchema: { type: 'object', properties, required } });
44
- if (r.action !== 'accept') throw new Cancelled(`Cancelled by the user (${r.action}); nothing was changed.`);
45
- return r.content || {};
46
- }
47
-
48
- /** A yes/no confirmation form; resolves only on yes. */
49
- async function confirm(server, message) {
50
- const a = await ask(server, message, { confirm: { type: 'boolean', title: 'Go ahead', default: true } });
51
- if (!a.confirm) throw new Cancelled('Not confirmed by the user; nothing was changed.');
52
- }
53
-
54
- export function buildServer(env = process.env) {
48
+ export function buildServer(env = process.env, opts = {}) {
55
49
  const ctx = () => loadContext(env);
56
50
  const base = ctx();
57
51
  const server = new McpServer({ name: 'harness-device', version: PKG.version });
52
+ const io = interaction(server, { transport: opts.transport || 'stdio' });
58
53
  const tool = (name, description, inputSchema, fn) =>
59
- server.registerTool(name, { description, inputSchema }, async (args) => {
54
+ (opts.allow && !opts.allow(name)) ? undefined : server.registerTool(name, { description, inputSchema }, async (args) => {
55
+ const a = args || {};
56
+ const c = ctx();
60
57
  try {
61
- return await fn(ctx(), args || {});
58
+ return await fn(c, a, {
59
+ ask: (message, properties, required) => io.ask(c, name, a, message, properties, required),
60
+ confirm: (message) => io.confirm(c, name, a, message),
61
+ });
62
62
  } catch (e) {
63
63
  if (e instanceof resources.ResourceDenied) return fail(`${e.message}\n${resources.summary(e.sample)}`);
64
- return e instanceof Cancelled ? text(e.message) : fail(e);
64
+ return e instanceof Cancelled || e instanceof NeedsUser ? text(e.message) : fail(e);
65
65
  }
66
66
  });
67
67
 
@@ -76,11 +76,11 @@ export function buildServer(env = process.env) {
76
76
 
77
77
  tool('proc_add', 'Register a long-running process so it keeps running across crashes and reboots, in tmux window proc-<name>. Use this instead of running servers in the foreground. Re-adding a name replaces it.',
78
78
  { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), dir: z.string().optional().describe('absolute working directory (asked if missing)'), command: z.string().optional().describe('one shell line, e.g. "npm run dev -- --port 5173" (asked if missing)'), ...FORCE },
79
- async (c, a) => {
79
+ async (c, a, u) => {
80
80
  await guard(c, a, `starting process ${a.name}`);
81
81
  if (!a.dir || !a.command) {
82
82
  const first = c.projects[0];
83
- const got = await ask(server, `Details for the long-running process "${a.name}"`, {
83
+ const got = await u.ask(`Details for the long-running process "${a.name}"`, {
84
84
  ...(a.dir ? {} : { dir: { type: 'string', title: 'Working directory', description: 'Absolute path, usually the project folder', ...(first ? { default: first.dir } : {}) } }),
85
85
  ...(a.command ? {} : { command: { type: 'string', title: 'Command', description: 'One shell line, e.g. npm run dev -- --port 5173' } }),
86
86
  });
@@ -91,9 +91,18 @@ export function buildServer(env = process.env) {
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('proc_remove', 'Stop and unregister a long-running process.', { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/) },
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 },
95
96
  async (c, a) => {
96
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `Stop and unregister process "${a.name}"? It will no longer restart or come back after a reboot.`);
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
+
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 },
104
+ async (c, a, u) => {
105
+ await u.confirm(`Stop and unregister process "${a.name}"? It will no longer restart or come back after a reboot.`);
97
106
  state.removeProc(c, a.name);
98
107
  return text(`proc ${a.name} removed`);
99
108
  });
@@ -147,8 +156,18 @@ export function buildServer(env = process.env) {
147
156
  }
148
157
 
149
158
  if (has(base, 'docker')) {
150
- tool('docker_summary', 'Containers (all) and Docker disk usage on this device.', {},
151
- async (c) => text(device.dockerSummary(c)));
159
+ tool('docker_summary', 'Containers (all) and Docker disk usage on this device, and running containers with no memory limit (which can take the whole machine).', {},
160
+ async (c) => text({ ...device.dockerSummary(c), noMemoryLimit: device.dockerUnlimited(c).map((x) => `${x.name}${x.managed ? ' (managed by Dokploy/compose/swarm: set its limit there)' : ''}`) }));
161
+ tool('docker_limit', 'Set a memory (and optional CPU) limit on a running container with docker update (asks the user first). memory defaults to RES_CONTAINER_MEM_DEFAULT. Containers Dokploy, compose or swarm manage are refused: their next deploy would drop the limit, so set it in Dokploy (or the compose file) instead.',
162
+ { container: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/), memory: z.string().regex(/^\d+(\.\d+)?[mMgG]$/).optional().describe('e.g. 512m, 1.5g'), cpus: z.number().min(0.1).max(64).optional(), ...CONFIRM },
163
+ async (c, a, u) => {
164
+ const row = device.dockerUnlimited(c, true).find((x) => x.name === a.container || x.id.startsWith(a.container));
165
+ if (!row) throw new Error(`No running container "${a.container}"`);
166
+ if (row.managed) throw new Error(`${row.name} is managed by Dokploy/compose/swarm; docker update would be lost on its next deploy. Set its memory limit in Dokploy (application → Advanced → Resources) or in its compose file.`);
167
+ const memory = a.memory || `${limits.mb(limits.limits(c.cfg).containerMem)}m`;
168
+ await u.confirm(`Limit container ${row.name} to ${memory} of RAM${a.cpus ? ` and ${a.cpus} CPUs` : ''}? If it needs more it is stopped by the kernel (out of memory) instead of slowing the whole machine.`);
169
+ return text(device.dockerLimit(c, row.name, memory, a.cpus));
170
+ });
152
171
  }
153
172
 
154
173
  if (has(base, 'ngrok')) {
@@ -156,12 +175,12 @@ export function buildServer(env = process.env) {
156
175
  async () => text(await device.ngrokStatus()));
157
176
  tool('ngrok_up', 'Open public ngrok URLs (the user approves this call). tunnels: groups "viewers" or "apps", or single tunnels such as "ttyd" or "app3000". ports: local app ports to expose (added to NGROK_APP_PORTS; opens just those when tunnels is empty). Viewers, and apps unless NGROK_APPS_PUBLIC=1, sit behind a login that the result includes: give it to the user. On a free ngrok plan open one tunnel at a time. Close them with ngrok_down when done.',
158
177
  { tunnels: z.array(z.string().regex(/^[A-Za-z0-9_-]+$/)).max(10).optional(), ports: z.array(z.number().int().min(1).max(65535)).max(10).optional() },
159
- async (c, a) => {
178
+ async (c, a, u) => {
160
179
  let tunnels = a.tunnels || [];
161
180
  let ports = a.ports || [];
162
181
  if (!tunnels.length && !ports.length) {
163
182
  const names = Object.keys(Object.assign({}, ...Object.values(ngrok.tunnels(c.cfg, c.platform.id))));
164
- const got = await ask(server, 'What should get a public URL?', {
183
+ const got = await u.ask('What should get a public URL?', {
165
184
  tunnel: { type: 'string', title: 'Tunnel', enum: [...names, 'app port'], description: 'An existing tunnel, or "app port" for a local server' },
166
185
  port: { type: 'integer', title: 'App port', minimum: 1, maximum: 65535, description: 'Only for "app port", e.g. 3000' },
167
186
  }, ['tunnel']);
@@ -172,20 +191,35 @@ export function buildServer(env = process.env) {
172
191
  }
173
192
  return text(await device.ngrokUp(c, { tunnels, ports }));
174
193
  });
175
- tool('ngrok_down', 'Close every ngrok tunnel on this device.', {},
176
- async (c) => {
177
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, 'Close every public ngrok URL on this device?');
194
+ tool('ngrok_down', 'Close every ngrok tunnel on this device (asks the user first).', { ...CONFIRM },
195
+ async (c, a, u) => {
196
+ await u.confirm('Close every public ngrok URL on this device?');
178
197
  c.platform.ngrokDown(c);
179
198
  return text('ngrok tunnels closed');
180
199
  });
181
200
  }
182
201
 
202
+ tool('disk_cleanup', 'Free disk space safely. Without apply it only lists what could go (Docker build cache, dangling images, old stopped containers not managed by Dokploy/compose, npm/pnpm/pip caches, the user journal, Playwright reports, harness logs) with sizes. apply=true removes the chosen items (all when items is empty) after the user confirms. Never removes volumes, databases or anything Dokploy runs.',
203
+ { apply: z.boolean().optional(), items: z.array(z.string().regex(/^[a-z0-9-]+$/)).max(20).optional().describe('ids from the listing; empty = all cleanable'), ...CONFIRM },
204
+ async (c, a, u) => {
205
+ const items = cleanup.plan(c);
206
+ const d = cleanup.describe(items);
207
+ if (!a.apply) return text({ ...d, next: 'To free it, ask the user which items (AskUserQuestion, multiSelect) and call disk_cleanup with apply=true and those items.' });
208
+ const ids = a.items || [];
209
+ const chosen = cleanup.describe(items.filter((i) => !i.listOnly && (!ids.length || ids.includes(i.id))));
210
+ if (!chosen.items.length) return text('Nothing to clean.');
211
+ await u.confirm(`Free about ${chosen.total} by removing: ${chosen.items.map((i) => `${i.id} (${i.size})`).join(', ')}? These are caches and leftovers that rebuild themselves; no data or running app is touched.`);
212
+ const r = cleanup.apply(c, ids, items);
213
+ state.event(c, `disk_cleanup freed ${r.freed}: ${r.done.map((x) => x.id).join(', ')}`);
214
+ return text(r);
215
+ });
216
+
183
217
  tool('resources', 'CPU, RAM and disk (persistent storage) on this device now, with the resource guard\'s level: ok, high or critical. Check it before heavy work (builds, test runs, containers, big installs).', {},
184
- async (c) => text(await resources.sample(c)));
218
+ async (c) => text({ ...(await resources.sample(c)), ...(c.env.HD_CONTAINER === '1' ? {} : { limits: limits.report(c) }) }));
185
219
 
186
220
  tool('upgrade', 'Upgrade harness-device on this device (the user approves this call); check=true only reports. npm installs go to the newest version (or `version`); source-folder installs apply the folder\'s current code. Runs in the background without stopping sessions or unchanged services. restart (default true) then restarts the device gracefully so every session, this one included, loads the new tools and resumes its conversation about a minute later: tell the user before calling.',
187
- { check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional(), restart: z.boolean().optional() },
188
- async (c, a) => {
221
+ { check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional(), restart: z.boolean().optional(), ...CONFIRM },
222
+ async (c, a, u) => {
189
223
  const chk = await upgrader.check(c, { to: a.version });
190
224
  if (a.check) return text(chk);
191
225
  const restart = a.restart !== false;
@@ -193,7 +227,7 @@ export function buildServer(env = process.env) {
193
227
  if (!folder && !chk.available) return text({ ...chk, note: chk.note || `already on ${chk.current}` });
194
228
  if (chk.source === 'none') return text({ ...chk, note: 'not installed on this device yet' });
195
229
  const what = folder ? `Apply the harness-device code in its source folder (${chk.current}) now?` : `Upgrade harness-device ${chk.current} → ${chk.latest} now?`;
196
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `${what} Sessions keep running while it installs${restart ? '; then the device restarts gracefully and every session (this one too) resumes its conversation in about a minute' : ''}.`);
230
+ await u.confirm(`${what} Sessions keep running while it installs${restart ? '; then the device restarts gracefully and every session (this one too) resumes its conversation in about a minute' : ''}.`);
197
231
  const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
198
232
  const args = [path.join(c.paths.bin, 'harness-device'), 'upgrade', ...(folder ? ['--apply'] : ['--to', chk.latest]), ...(restart ? ['--restart'] : []), ...(own ? ['--except', own] : [])];
199
233
  c.platform.spawnDetached(c, 'upgrade', args, path.join(c.paths.logs, 'upgrade.log'));
@@ -201,9 +235,9 @@ export function buildServer(env = process.env) {
201
235
  });
202
236
 
203
237
  tool('device_restart', 'Gracefully restart the whole device (the user approves this call): waits for other sessions to finish their turn, ends sessions and processes cleanly, saves the browser, restarts every service. This session ends too and resumes the same conversation about a minute later; tell the user before calling. Stopping the device is done at the machine (harness-device stop), not from a session.',
204
- { now: z.boolean().optional().describe("don't wait for other sessions to finish their turn") },
205
- async (c, a) => {
206
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, 'Restart the whole device now? Every session (this one too) ends and resumes its conversation in about a minute; public URLs close.');
238
+ { now: z.boolean().optional().describe("don't wait for other sessions to finish their turn"), ...CONFIRM },
239
+ async (c, a, u) => {
240
+ await u.confirm('Restart the whole device now? Every session (this one too) ends and resumes its conversation in about a minute; public URLs close.');
207
241
  // The calling session's own turn is still open: don't wait for it.
208
242
  const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
209
243
  const bin = path.join(c.paths.bin, 'harness-device');
@@ -215,9 +249,9 @@ export function buildServer(env = process.env) {
215
249
  async (c) => text(Object.fromEntries(Object.keys(SETTABLE_KEYS).map((k) => [k, c.cfg[k] ?? '']))));
216
250
  tool('config_set', `Change one device setting (the user approves this call). Never edit files in the device home instead. Keys: ${Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k} (${d})`).join('; ')}. Secrets, capabilities, projects and service ports are changed on the machine, not here.`,
217
251
  { key: z.enum(Object.keys(SETTABLE_KEYS)).optional(), value: z.string().max(200).optional() },
218
- async (c, a) => {
252
+ async (c, a, u) => {
219
253
  if (!a.key || a.value === undefined) {
220
- const got = await ask(server, 'Change a device setting', {
254
+ const got = await u.ask('Change a device setting', {
221
255
  ...(a.key ? {} : { key: { type: 'string', title: 'Setting', enum: Object.keys(SETTABLE_KEYS), description: Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k}: ${d}`).join('; ') } }),
222
256
  value: { type: 'string', title: 'Value', maxLength: 200, ...(a.key ? { description: SETTABLE_KEYS[a.key] } : {}) },
223
257
  });
@@ -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'];
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. */
@@ -89,6 +89,8 @@ export function jobs(ctx, detect = true) {
89
89
  'harness-ttyd': { args: [run('harness-ttyd'), ttyd, '-i', 'lo0', '-p', c.TTYD_PORT, '-t', 'titleFixed=harness-device', tmux, 'attach', '-r', '-f', 'ignore-size', '-t', `=${c.SESSION}`] },
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
+ 'harness-serve': { args: [run('harness-serve'), b('harness-device'), 'serve'] },
93
+ 'harness-pool': { args: [run('harness-pool'), b('harness-device'), 'pool', 'link'] },
92
94
  };
93
95
  return (u) => {
94
96
  const d = def[u];
@@ -5,6 +5,7 @@ import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
7
  import { PKG_ROOT, run, capture, ok, which, render, writeFile, color } from '../util.js';
8
+ import * as limits from '../limits.js';
8
9
 
9
10
  export const id = 'linux';
10
11
  export const label = 'Linux (systemd user services)';
@@ -32,6 +33,7 @@ export function unitVars(ctx, detect = true) {
32
33
  TTYD_BIN: (detect && which('ttyd', ctx.env)) || '/usr/bin/ttyd',
33
34
  CAPABILITIES: ctx.caps.map((c) => c.id).join(','),
34
35
  WANTS: ctx.units.map(unitName).join(' '),
36
+ ...limits.unitVars(ctx.cfg),
35
37
  };
36
38
  }
37
39
 
@@ -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
+ }
@@ -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
+ }
@@ -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
+ }
@@ -130,7 +130,8 @@ export const interaction = {
130
130
  guidance: () => `## Asking the user
131
131
  The user usually drives this session remotely (phone, claude.ai) and answers by tapping, so ask with interactive prompts, not prose:
132
132
  - **When you need a decision, preference or value, use the \`AskUserQuestion\` tool**, never a question written in your reply. 1-4 questions, 2-4 options each; put the recommended option first and end its label with "(Recommended)"; use multiSelect when choices combine; use the preview field to compare layouts or code. The user can always pick "Other" and type.
133
- - harness-device tools may show their own form (MCP elicitation) for missing details or to confirm something that stops or exposes things. Answer through that; don't ask the same thing again.
133
+ - harness-device tools that stop, expose or change things confirm first. In a Remote Control session (and over \`harness-device serve\`) they do nothing on the first call and reply with what to ask: ask it with \`AskUserQuestion\`, and only on "Go ahead" call the tool again with the \`confirm_token\` it gave (one use, those exact arguments, 10 minutes). Missing details come back the same way. In a local terminal they may show a form instead; answer that and don't ask again.
134
+ - Nothing may wait on this machine's terminal: the user is usually not at it. If something would need a local prompt, ask through \`AskUserQuestion\` instead. For hands-on access the user has the web terminal and display (\`viewers\` tool, opened publicly with \`ngrok_up\`).
134
135
  - Never ask for passwords, API keys or tokens in a question or form. Secrets are entered on the machine (\`harness-device secrets set KEY\`); say that instead.
135
136
  - Never tell the user to run commands on the machine. Ask with options, then do it yourself through the tools.
136
137
  - When a tool returns something the user needs (a URL, a login, a file path), write it plainly in your reply, since prompts disappear once answered.`,
@@ -189,6 +190,10 @@ export function pathRule(tool, abs, home) {
189
190
  */
190
191
  export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-device install:*)',
191
192
  'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)',
193
+ // The serve owner password, and approving/revoking apps, are the owner's.
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:*)',
192
197
  // Stopping ends every session and none could start the device again; restart goes through device_restart.
193
198
  'Bash(harness-device stop:*)', 'Bash(harness-device start:*)', 'Bash(harness-device restart)', 'Bash(harness-device restart --:*)'];
194
199