@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/config.js CHANGED
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import os from 'node:os';
7
7
  import path from 'node:path';
8
8
  import crypto from 'node:crypto';
9
+ import * as limitsMod from './limits.js';
9
10
 
10
11
  export const DEFAULT_CAPABILITIES = 'browser,playwright,display,shell,system,sqlite,docker,graphify';
11
12
  export const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/;
@@ -28,6 +29,7 @@ export function paths(env = process.env) {
28
29
  pkg: path.join(home, 'pkg'),
29
30
  fleet: path.join(home, 'fleet.tsv'),
30
31
  ngrokEnv: path.join(home, 'ngrok.env'),
32
+ pool: path.join(home, 'pool.env'),
31
33
  state: path.join(home, 'state'),
32
34
  logs: path.join(home, 'logs'),
33
35
  profile: path.join(home, 'chromium-profile'),
@@ -73,6 +75,29 @@ export function defaults(env = process.env) {
73
75
  RES_CPU_CRITICAL: '95',
74
76
  RES_MEM_CRITICAL: '5',
75
77
  RES_DISK_CRITICAL: '3',
78
+ // How device tools ask the user: auto (AskUserQuestion in Remote Control
79
+ // sessions, a form in local ones) | tool (always AskUserQuestion) | elicit.
80
+ ASK_MODE: 'auto',
81
+ ELICIT_TIMEOUT_SECONDS: '90',
82
+ // Safe maximums (empty = worked out from this machine's RAM and cores;
83
+ // see src/limits.js). Memory: 25% of RAM, 1536 (MB), 512M or 1.5G.
84
+ RES_RESERVE_MEM: '',
85
+ RES_HARNESS_MEM_MAX: '',
86
+ RES_PROC_MEM_MAX: '',
87
+ RES_PROC_CPU_MAX: '',
88
+ RES_BROWSER_MEM_MAX: '',
89
+ RES_CONTAINER_MEM_DEFAULT: '',
90
+ MAX_SESSIONS: '',
91
+ MAX_PROCS: '',
92
+ RES_WATCHDOG: 'on',
93
+ // `harness-device serve` (capability "serve"): MCP over HTTP with OAuth.
94
+ // Bind address, and the https URL clients use (Traefik/Dokploy or ngrok in front).
95
+ SERVE_HOST: '127.0.0.1',
96
+ SERVE_PORT: '7700',
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',
76
101
  };
77
102
  }
78
103
 
@@ -184,6 +209,17 @@ export function validateConfig(cfg, env = process.env) {
184
209
  if (!/^\d+$/.test(String(cfg.AUTO_UPGRADE_HOURS)) || Number(cfg.AUTO_UPGRADE_HOURS) < 1) errs.push('AUTO_UPGRADE_HOURS must be a whole number of hours, at least 1.');
185
210
  if (!['on', 'off'].includes(String(cfg.RESOURCE_GUARD))) errs.push('RESOURCE_GUARD must be on or off.');
186
211
  if (!/^\d+$/.test(String(cfg.RES_WAIT_SECONDS)) || Number(cfg.RES_WAIT_SECONDS) > 3600) errs.push('RES_WAIT_SECONDS must be 0-3600.');
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.');
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.');
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.');
216
+ if (cfg.SERVE_PUBLIC_URL) {
217
+ let u;
218
+ try { u = new URL(cfg.SERVE_PUBLIC_URL); } catch { /* reported below */ }
219
+ if (!u || !(u.protocol === 'https:' || ['localhost', '127.0.0.1'].includes(u.hostname)) || u.search || u.hash) errs.push('SERVE_PUBLIC_URL must be an https URL (no query), e.g. https://mcp.example.com.');
220
+ }
221
+ if (!['auto', 'tool', 'elicit'].includes(String(cfg.ASK_MODE))) errs.push('ASK_MODE must be auto, tool or elicit.');
222
+ if (!/^\d+$/.test(String(cfg.ELICIT_TIMEOUT_SECONDS)) || Number(cfg.ELICIT_TIMEOUT_SECONDS) < 10 || Number(cfg.ELICIT_TIMEOUT_SECONDS) > 600) errs.push('ELICIT_TIMEOUT_SECONDS must be 10-600.');
187
223
  for (const k of ['RES_CPU_CRITICAL', 'RES_MEM_CRITICAL', 'RES_DISK_CRITICAL']) {
188
224
  if (!/^\d+$/.test(String(cfg[k])) || Number(cfg[k]) < 1 || Number(cfg[k]) > 100) errs.push(`${k} must be a percentage, 1-100.`);
189
225
  }
@@ -213,6 +249,16 @@ function shq(v) {
213
249
  return `'${s}'`;
214
250
  }
215
251
 
252
+ /** Set (or with null, remove) one KEY='value' line in secrets.env, mode 600. */
253
+ export function setSecret(file, key, value) {
254
+ const lines = fs.existsSync(file) ? fs.readFileSync(file, 'utf8').split('\n').filter((l) => !l.startsWith(`${key}=`)) : [];
255
+ while (lines.length && lines[lines.length - 1] === '') lines.pop();
256
+ if (value != null) lines.push(`${key}='${value}'`);
257
+ fs.mkdirSync(path.dirname(file), { recursive: true });
258
+ fs.writeFileSync(file, lines.join('\n') + '\n', { mode: 0o600 });
259
+ fs.chmodSync(file, 0o600);
260
+ }
261
+
216
262
  /** runtime.env: what the shell scripts and systemd units read. */
217
263
  export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformId = 'linux' } = {}) {
218
264
  const p = paths(env);
@@ -238,6 +284,8 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
238
284
  HD_PLATFORM: platformId,
239
285
  HD_AUTO_UPGRADE: cfg.AUTO_UPGRADE,
240
286
  HD_AUTO_UPGRADE_HOURS: cfg.AUTO_UPGRADE_HOURS,
287
+ HD_WATCHDOG: cfg.RES_WATCHDOG || 'on',
288
+ ...limitsMod.runtimeVars(cfg),
241
289
  // Linux: the virtual display. macOS: the real screen, no DISPLAY.
242
290
  ...(platformId === 'linux' ? { DISPLAY: `:${cfg.DISPLAY_NUM}` } : {}),
243
291
  // Services start with a bare PATH; keep the one the installer ran with, so
@@ -280,8 +328,19 @@ export const SETTABLE_KEYS = {
280
328
  RES_CPU_CRITICAL: 'CPU busy % that counts as critical',
281
329
  RES_MEM_CRITICAL: 'available RAM % at or below which the device is critical',
282
330
  RES_DISK_CRITICAL: 'free disk % at or below which the device is critical',
331
+ ASK_MODE: 'how device tools ask the user: auto (AskUserQuestion in Remote Control sessions, a form locally), tool (always AskUserQuestion) or elicit (form when the client supports it)',
332
+ RES_RESERVE_MEM: 'RAM always kept free for the OS, Docker and other apps; heavy new work is refused below it (empty = max(1 GB, 12%); e.g. 1536, 1.5G, 15%)',
333
+ RES_HARNESS_MEM_MAX: 'RAM for everything harness-device runs together (sessions, processes, browser); over it the largest registered process is stopped (empty = 60%)',
334
+ RES_PROC_MEM_MAX: 'RAM per registered process (empty = 25%; needs install to apply on Linux)',
335
+ RES_PROC_CPU_MAX: 'CPU % per registered process, 100 = one core (empty = half the cores; needs install to apply on Linux)',
336
+ RES_BROWSER_MEM_MAX: 'RAM for the device Chromium (empty = min(1.5 GB, 20%); needs install to apply on Linux)',
337
+ RES_CONTAINER_MEM_DEFAULT: 'memory limit suggested for Docker containers that have none (empty = 512M)',
338
+ MAX_SESSIONS: 'most agent sessions at once (empty = number of cores, at least 2)',
339
+ MAX_PROCS: 'most registered processes at once (empty = 6)',
340
+ RES_WATCHDOG: 'on = stop registered processes and the browser that stay over their limits (they restart), off = only report',
341
+ ELICIT_TIMEOUT_SECONDS: 'how long a form waits for an answer before the tool falls back to AskUserQuestion (10-600)',
283
342
  };
284
- const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS|AUTO_UPGRADE|RESOURCE_GUARD)/;
343
+ const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS|AUTO_UPGRADE|RESOURCE_GUARD|RES_PROC_|RES_BROWSER_|RES_WATCHDOG)/;
285
344
 
286
345
  /** Validate and save one settable key; returns { key, value, needsInstall }. */
287
346
  export function setConfigValue(key, value, env = process.env) {
@@ -0,0 +1,26 @@
1
+ // HD_CONTAINER=1: `harness-device serve` as a Docker container (a Dokploy
2
+ // app). It sees the host's Docker (the mounted socket), RAM and CPU (/proc is
3
+ // the host's), and disk through a read-only mount of / at HD_HOST_ROOT. It
4
+ // has no tmux sessions, processes or browser, so only the tools that make
5
+ // sense there are served.
6
+ //
7
+ // Configuration comes from the environment (Dokploy's Environment tab),
8
+ // not config.env: DEVICE, SERVE_PUBLIC_URL, SERVE_PORT, SERVE_OWNER_PASSWORD,
9
+ // and the RES_* limits.
10
+
11
+ export const isContainer = (env = process.env) => env.HD_CONTAINER === '1';
12
+
13
+ /** Tools a container can actually do something with. */
14
+ export const CONTAINER_TOOLS = ['resources', 'docker_summary', 'docker_limit', 'disk_cleanup'];
15
+
16
+ const FROM_ENV = /^(DEVICE|SERVE_PUBLIC_URL|SERVE_PORT|RES_[A-Z_]+|RESOURCE_GUARD|ASK_MODE)$/;
17
+
18
+ /** The container's config: defaults + file, then the environment, with a fixed capability set. */
19
+ export function containerConfig(cfg, env = process.env) {
20
+ const out = { ...cfg };
21
+ for (const [k, v] of Object.entries(env)) if (FROM_ENV.test(k) && v !== undefined && v !== '') out[k] = v;
22
+ out.SERVE_HOST = env.SERVE_HOST || '0.0.0.0';
23
+ out.CAPABILITIES = 'shell,system,docker';
24
+ for (const k of Object.keys(out)) if (k.startsWith('PROJECT_')) delete out[k];
25
+ return out;
26
+ }
package/src/context.js CHANGED
@@ -3,6 +3,7 @@ import { loadConfig, paths, projects, capabilityIds, mcpServers, parseEnv } from
3
3
  import { resolveCapabilities, unitsFor } from './capabilities.js';
4
4
  import { platform as detectPlatform } from './platform/index.js';
5
5
  import * as claude from './providers/claude.js';
6
+ import { isContainer, containerConfig } from './container.js';
6
7
 
7
8
  export const PROVIDERS = { claude };
8
9
 
@@ -36,7 +37,9 @@ function withServicePath(env) {
36
37
  export function loadContext(rawEnv = process.env, { dryRun = false } = {}) {
37
38
  const plat = detectPlatform(rawEnv);
38
39
  const env = withServicePath(plat.userEnv(rawEnv));
39
- const { cfg, exists } = loadConfig(env);
40
+ const loaded = loadConfig(env);
41
+ const cfg = isContainer(env) ? containerConfig(loaded.cfg, env) : loaded.cfg;
42
+ const exists = loaded.exists || isContainer(env);
40
43
  const caps = resolveCapabilities(capabilityIds(cfg));
41
44
  return {
42
45
  env,
package/src/device.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { spawn } from 'node:child_process';
7
- import { capture, ok, httpJson, which } from './util.js';
7
+ import { capture, ok, run, httpJson, which } from './util.js';
8
8
  import { listSessions, listProcs, recentEvents } from './state.js';
9
9
  import { loadConfig, saveConfig, mergePorts } from './config.js';
10
10
  import * as ngrok from './ngrok.js';
@@ -41,6 +41,26 @@ export function dockerSummary(ctx) {
41
41
  return { installed: true, reachable: ok('docker', ['info'], { timeout: 20000, env: ctx.env }), containers: ps, df };
42
42
  }
43
43
 
44
+ const MANAGED = /dokploy|com\.docker\.swarm|com\.docker\.compose|coolify/i;
45
+
46
+ /** Running containers; all of them with `all`, else only those with no memory limit. */
47
+ export function dockerUnlimited(ctx, all = false) {
48
+ if (!which('docker', ctx.env)) return [];
49
+ const ids = capture('docker', ['ps', '-q'], { env: ctx.env }).split('\n').filter(Boolean);
50
+ if (!ids.length) return [];
51
+ const out = capture('docker', ['inspect', '--format', '{{.Id}}\t{{.Name}}\t{{.HostConfig.Memory}}\t{{json .Config.Labels}}', ...ids], { env: ctx.env, timeout: 30000 });
52
+ return out.split('\n').filter(Boolean).map((l) => {
53
+ const [id, name, mem, labels] = l.split('\t');
54
+ return { id, name: name.replace(/^\//, ''), memory: Number(mem) || 0, managed: MANAGED.test(labels || '') || MANAGED.test(name) };
55
+ }).filter((x) => all || !x.memory);
56
+ }
57
+
58
+ export function dockerLimit(ctx, name, memory, cpus) {
59
+ const args = ['update', '--memory', memory, '--memory-swap', memory, ...(cpus ? ['--cpus', String(cpus)] : []), name];
60
+ run('docker', args, { env: ctx.env });
61
+ return `${name}: memory limit ${memory}${cpus ? `, ${cpus} CPUs` : ''}`;
62
+ }
63
+
44
64
  export async function status(ctx) {
45
65
  const cdp = await httpJson(`http://127.0.0.1:${ctx.cfg.CDP_PORT}/json/version`, 2000);
46
66
  return {
package/src/doctor.js CHANGED
@@ -19,6 +19,16 @@ export async function collect(ctx) {
19
19
  for (const r of await cap.checks(ctx)) out.push({ group: cap.id, ...r });
20
20
  }
21
21
  for (const r of ctx.provider.checks(ctx)) out.push({ group: ctx.provider.id, ...r });
22
+ if (ctx.platform.id === 'linux') {
23
+ // Kernel-held limits need the memory and cpu controllers delegated to the user manager.
24
+ const uid = process.getuid ? process.getuid() : 0;
25
+ let ctl = '';
26
+ try { ctl = fs.readFileSync(`/sys/fs/cgroup/user.slice/user-${uid}.slice/user@${uid}.service/cgroup.controllers`, 'utf8'); } catch { /* cgroup v1 or no systemd */ }
27
+ const okCg = /\bmemory\b/.test(ctl) && /\bcpu\b/.test(ctl);
28
+ out.push({ group: 'limits', name: 'kernel-held limits (cgroup memory + cpu delegated)', ok: okCg, warn: !okCg,
29
+ msg: okCg ? undefined : 'not available: the watchdog holds the limits instead (every 30s)',
30
+ fix: 'sudo mkdir -p /etc/systemd/system/user@.service.d && printf "[Service]\\nDelegate=cpu cpuset io memory pids\\n" | sudo tee /etc/systemd/system/user@.service.d/delegate.conf && sudo systemctl daemon-reload, then log in again' });
31
+ }
22
32
  return out;
23
33
  }
24
34
 
package/src/limits.js ADDED
@@ -0,0 +1,248 @@
1
+ // Safe maximums for what harness-device starts, and the watchdog that holds
2
+ // them. Defaults come from the machine (RAM, cores), so an 8 GB / 4-core box
3
+ // keeps about 1 GB free for the OS, Docker and Dokploy apps whatever sessions do.
4
+ //
5
+ // Enforcement:
6
+ // - Linux: registered processes run in their own systemd scope with
7
+ // MemoryMax/CPUQuota (hd-proc-loop); Chromium's unit has MemoryMax; the
8
+ // tmux service (sessions + processes) has MemoryHigh. The kernel holds them.
9
+ // - Everywhere (macOS, and Linux without cgroup delegation): enforce() runs
10
+ // every 30s. A registered process or the browser over its limit for 3
11
+ // readings in a row is stopped (its loop restarts it, with backoff), and
12
+ // over the harness total the largest registered process goes first.
13
+ // Agent sessions are measured, never killed. Nothing outside the harness
14
+ // (Docker, Dokploy apps) is touched.
15
+ // - New work: proc_add / session new refuse beyond MAX_PROCS / MAX_SESSIONS;
16
+ // heavy tools refuse while available RAM is under the reserve.
17
+
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { capture } from './util.js';
22
+
23
+ const MiB = 1024 ** 2;
24
+ const GiB = 1024 ** 3;
25
+ export const STRIKES = 3;
26
+
27
+ /** '' (auto) | '25%' (of RAM) | '1536' (MB) | '1.5G' | '512M' → bytes, or null for auto. */
28
+ export function parseMem(v, total) {
29
+ const s = String(v ?? '').trim();
30
+ if (!s) return null;
31
+ const m = s.match(/^(\d+(?:\.\d+)?)\s*(%|[MG]B?|)$/i);
32
+ if (!m) throw new Error(`Not a memory size: "${s}" (use 25%, 1536 (MB), 512M or 1.5G)`);
33
+ const n = Number(m[1]);
34
+ const u = m[2].toUpperCase();
35
+ if (u === '%') return Math.round((total * n) / 100);
36
+ if (u.startsWith('G')) return Math.round(n * GiB);
37
+ return Math.round(n * MiB);
38
+ }
39
+
40
+ export const MEM_KEYS = ['RES_RESERVE_MEM', 'RES_HARNESS_MEM_MAX', 'RES_PROC_MEM_MAX', 'RES_BROWSER_MEM_MAX', 'RES_CONTAINER_MEM_DEFAULT'];
41
+
42
+ /** Validation errors for the limit settings (used by validateConfig). */
43
+ export function validate(cfg) {
44
+ const errs = [];
45
+ for (const k of MEM_KEYS) {
46
+ try { parseMem(cfg[k], GiB); } catch (e) { errs.push(`${k}: ${e.message}`); }
47
+ if (/%$/.test(String(cfg[k] || '')) && (parseFloat(cfg[k]) <= 0 || parseFloat(cfg[k]) > 100)) errs.push(`${k} must be 1-100%.`);
48
+ }
49
+ if (cfg.RES_PROC_CPU_MAX && (!/^\d+$/.test(String(cfg.RES_PROC_CPU_MAX)) || Number(cfg.RES_PROC_CPU_MAX) < 10)) errs.push('RES_PROC_CPU_MAX must be a CPU % (100 = one core), at least 10.');
50
+ for (const k of ['MAX_SESSIONS', 'MAX_PROCS']) {
51
+ if (cfg[k] && (!/^\d+$/.test(String(cfg[k])) || Number(cfg[k]) < 1 || Number(cfg[k]) > 100)) errs.push(`${k} must be a number, 1-100.`);
52
+ }
53
+ if (cfg.RES_WATCHDOG && !['on', 'off'].includes(String(cfg.RES_WATCHDOG))) errs.push('RES_WATCHDOG must be on or off.');
54
+ return errs;
55
+ }
56
+
57
+ /** The limits in force (bytes, CPU % where 100 = one core). */
58
+ export function limits(cfg = {}, { total = os.totalmem(), cores = os.cpus().length || 1 } = {}) {
59
+ const pick = (k, auto) => parseMem(cfg[k], total) ?? auto;
60
+ const reserve = pick('RES_RESERVE_MEM', Math.max(GiB, Math.round(total * 0.12)));
61
+ const harness = Math.min(pick('RES_HARNESS_MEM_MAX', Math.round(total * 0.6)), total - reserve);
62
+ return {
63
+ totalMem: total,
64
+ cores,
65
+ reserveMem: reserve,
66
+ harnessMem: harness,
67
+ procMem: Math.min(pick('RES_PROC_MEM_MAX', Math.round(total * 0.25)), harness),
68
+ procCpu: Number(cfg.RES_PROC_CPU_MAX) || Math.max(100, Math.round(cores * 50)),
69
+ browserMem: Math.min(pick('RES_BROWSER_MEM_MAX', Math.min(1.5 * GiB, Math.round(total * 0.2))), harness),
70
+ containerMem: pick('RES_CONTAINER_MEM_DEFAULT', 512 * MiB),
71
+ maxSessions: Number(cfg.MAX_SESSIONS) || Math.max(2, cores),
72
+ maxProcs: Number(cfg.MAX_PROCS) || 6,
73
+ watchdog: String(cfg.RES_WATCHDOG || 'on') !== 'off',
74
+ };
75
+ }
76
+
77
+ export const mb = (b) => Math.round(b / MiB);
78
+ export const humanMem = (b) => (b >= GiB ? `${(b / GiB).toFixed(1)} GB` : `${mb(b)} MB`);
79
+
80
+ /** runtime.env values the shell scripts use (hd-proc-loop's systemd scope). */
81
+ export function runtimeVars(cfg) {
82
+ const l = limits(cfg);
83
+ return { HD_PROC_MEM_MAX_MB: String(mb(l.procMem)), HD_PROC_CPU_MAX: String(l.procCpu) };
84
+ }
85
+
86
+ /** Template values for the systemd units. */
87
+ export function unitVars(cfg) {
88
+ const l = limits(cfg);
89
+ return { BROWSER_MEM_MAX: `${mb(l.browserMem)}M`, BROWSER_MEM_HIGH: `${mb(l.browserMem * 0.9)}M`, HARNESS_MEM_HIGH: `${mb(l.harnessMem)}M` };
90
+ }
91
+
92
+ /** "1-02:03:04", "02:03:04", "3:04.56" → seconds. */
93
+ export function cpuSeconds(t) {
94
+ const [d, rest] = String(t).includes('-') ? String(t).split('-') : ['0', String(t)];
95
+ return rest.split(':').map(Number).reduce((a, x) => a * 60 + x, 0) + Number(d) * 86400;
96
+ }
97
+
98
+ /** `ps -A -o pid=,ppid=,rss=,time=,args=` → Map pid → { pid, ppid, rss (bytes), cpu (s), args }. */
99
+ export function parsePs(out) {
100
+ const m = new Map();
101
+ for (const line of String(out).split('\n')) {
102
+ const f = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
103
+ if (!f) continue;
104
+ m.set(Number(f[1]), { pid: Number(f[1]), ppid: Number(f[2]), rss: Number(f[3]) * 1024, cpu: cpuSeconds(f[4]), args: f[5] });
105
+ }
106
+ return m;
107
+ }
108
+
109
+ /** pid and all its descendants. */
110
+ export function tree(procs, root) {
111
+ const kids = new Map();
112
+ for (const p of procs.values()) (kids.get(p.ppid) || kids.set(p.ppid, []).get(p.ppid)).push(p.pid);
113
+ const out = [];
114
+ const stack = [root];
115
+ while (stack.length) {
116
+ const p = stack.pop();
117
+ if (!procs.has(p) || out.includes(p)) continue;
118
+ out.push(p);
119
+ stack.push(...(kids.get(p) || []));
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /**
125
+ * The harness's process groups: sessions (rc-*), registered processes
126
+ * (proc-*, measured below their loop so stopping them lets the loop restart),
127
+ * and the browser.
128
+ */
129
+ export function groups(ctx, procs = parsePs(capture('ps', ['-A', '-o', 'pid=,ppid=,rss=,time=,args='], { env: ctx.env, timeout: 10000 }))) {
130
+ const out = [];
131
+ const panes = capture('tmux', ['list-panes', '-s', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}\t#{pane_pid}'], { env: ctx.env });
132
+ for (const line of panes.split('\n')) {
133
+ const [win, pid] = line.split('\t');
134
+ if (!pid) continue;
135
+ if (win.startsWith('proc-')) {
136
+ const loop = Number(pid);
137
+ const pids = tree(procs, loop).filter((p) => p !== loop);
138
+ out.push({ name: win, kind: 'proc', pids, loop });
139
+ } else if (win.startsWith('rc-')) {
140
+ out.push({ name: win, kind: 'session', pids: tree(procs, Number(pid)) });
141
+ }
142
+ }
143
+ const port = `--remote-debugging-port=${ctx.cfg.CDP_PORT}`;
144
+ const roots = [...procs.values()].filter((p) => p.args.includes(port) && !(procs.get(p.ppid)?.args || '').includes(port));
145
+ if (roots.length) out.push({ name: 'browser', kind: 'browser', pids: roots.flatMap((r) => tree(procs, r.pid)) });
146
+ for (const g of out) {
147
+ g.rss = g.pids.reduce((a, p) => a + (procs.get(p)?.rss || 0), 0);
148
+ g.cpuSeconds = g.pids.reduce((a, p) => a + (procs.get(p)?.cpu || 0), 0);
149
+ }
150
+ return out;
151
+ }
152
+
153
+ /**
154
+ * Pure decision step. prev: { at, cpu: {name: s}, strikes: {name: n} }.
155
+ * Returns { actions: [{ name, kind, reason }], next } where next is the state to keep.
156
+ */
157
+ export function decide(gs, l, prev = {}, now = Date.now()) {
158
+ const dt = prev.at ? (now - prev.at) / 1000 : 0;
159
+ const strikes = {};
160
+ const cpu = {};
161
+ const actions = [];
162
+ const over = (key, is) => { strikes[key] = is ? ((prev.strikes || {})[key] || 0) + 1 : 0; return strikes[key] >= STRIKES; };
163
+ for (const g of gs) {
164
+ cpu[g.name] = g.cpuSeconds;
165
+ const before = (prev.cpu || {})[g.name];
166
+ g.cpuPct = dt > 0 && before !== undefined ? Math.max(0, Math.round((100 * (g.cpuSeconds - before)) / dt)) : null;
167
+ if (g.kind === 'session') continue;
168
+ const memMax = g.kind === 'browser' ? l.browserMem : l.procMem;
169
+ const memOver = g.rss > memMax;
170
+ const cpuOver = g.kind === 'proc' && g.cpuPct !== null && g.cpuPct > l.procCpu;
171
+ if (over(g.name, memOver || cpuOver)) {
172
+ actions.push({ name: g.name, kind: g.kind, reason: memOver ? `using ${humanMem(g.rss)}, limit ${humanMem(memMax)}` : `using ${g.cpuPct}% CPU, limit ${l.procCpu}%` });
173
+ }
174
+ }
175
+ const total = gs.reduce((a, g) => a + g.rss, 0);
176
+ if (over('total', total > l.harnessMem)) {
177
+ const victim = gs.filter((g) => g.kind === 'proc' && !actions.some((a) => a.name === g.name)).sort((a, b) => b.rss - a.rss)[0];
178
+ if (victim) actions.push({ name: victim.name, kind: 'proc', reason: `harness total ${humanMem(total)} is over ${humanMem(l.harnessMem)}; ${victim.name} is the largest registered process (${humanMem(victim.rss)})` });
179
+ }
180
+ for (const a of actions) strikes[a.name] = 0;
181
+ if (actions.some((a) => a.reason.startsWith('harness total'))) strikes.total = 0;
182
+ return { actions, total, next: { at: now, cpu, strikes } };
183
+ }
184
+
185
+ function stopTree(pids) {
186
+ const alive = (p) => { try { process.kill(p, 0); return true; } catch { return false; } };
187
+ for (const p of pids) { try { process.kill(p, 'SIGTERM'); } catch { /* gone */ } }
188
+ const until = Date.now() + 10000;
189
+ while (Date.now() < until && pids.some(alive)) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250);
190
+ for (const p of pids) if (alive(p)) { try { process.kill(p, 'SIGKILL'); } catch { /* gone */ } }
191
+ }
192
+
193
+ const stateFile = (ctx) => path.join(ctx.paths.state, 'watchdog.json');
194
+
195
+ /** One watchdog pass: measure, decide, act. Returns what it saw and did. */
196
+ export async function enforce(ctx, { act = true } = {}) {
197
+ const l = limits(ctx.cfg);
198
+ let prev = {};
199
+ try { prev = JSON.parse(fs.readFileSync(stateFile(ctx), 'utf8')); } catch { /* first run */ }
200
+ const gs = groups(ctx);
201
+ const { actions, total, next } = decide(gs, l, prev);
202
+ if (act && l.watchdog) {
203
+ const { event } = await import('./state.js');
204
+ for (const a of actions) {
205
+ const g = gs.find((x) => x.name === a.name);
206
+ event(ctx, `limits: stopped ${a.name} (${a.reason})${a.kind === 'proc' ? '; it restarts with backoff' : ''}`);
207
+ if (a.kind === 'browser') {
208
+ const { restartService } = await import('./device.js');
209
+ try { restartService(ctx, 'chromium'); } catch { stopTree(g.pids); }
210
+ } else stopTree([...g.pids].reverse());
211
+ }
212
+ fs.mkdirSync(ctx.paths.state, { recursive: true });
213
+ fs.writeFileSync(stateFile(ctx), JSON.stringify(next));
214
+ }
215
+ return { limits: l, total, groups: gs.map(({ pids, loop, ...g }) => ({ ...g, processes: pids.length })), actions: act && l.watchdog ? actions : [] };
216
+ }
217
+
218
+ /** Limits next to current use, for the resources tool and CLI. */
219
+ export function report(ctx, gs = groups(ctx)) {
220
+ const l = limits(ctx.cfg);
221
+ const total = gs.reduce((a, g) => a + g.rss, 0);
222
+ const n = (k) => gs.filter((g) => g.kind === k).length;
223
+ return {
224
+ reserveMem: `${humanMem(l.reserveMem)} kept free for the OS, Docker and other apps`,
225
+ harnessMem: `${humanMem(total)} used of ${humanMem(l.harnessMem)} (sessions + processes + browser)`,
226
+ perProcess: `${humanMem(l.procMem)} RAM, ${l.procCpu}% CPU (100% = one core)`,
227
+ browser: `${humanMem(gs.find((g) => g.kind === 'browser')?.rss || 0)} used of ${humanMem(l.browserMem)}`,
228
+ sessions: `${n('session')} of ${l.maxSessions}`,
229
+ processes: `${n('proc')} of ${l.maxProcs}`,
230
+ watchdog: l.watchdog ? 'on (every 30s; 3 readings over a limit stop the process, its loop restarts it)' : 'off',
231
+ top: gs.filter((g) => g.rss).sort((a, b) => b.rss - a.rss).slice(0, 6).map((g) => `${g.name} ${humanMem(g.rss)}`),
232
+ };
233
+ }
234
+
235
+ /** Refuse new work that would pass a cap; `what` is 'proc' or 'session'. */
236
+ export function checkCap(ctx, what, current) {
237
+ const l = limits(ctx.cfg);
238
+ const max = what === 'proc' ? l.maxProcs : l.maxSessions;
239
+ if (current >= max) {
240
+ const key = what === 'proc' ? 'MAX_PROCS' : 'MAX_SESSIONS';
241
+ throw new Error(`Refused: ${current} ${what === 'proc' ? 'registered processes' : 'sessions'} already, the safe maximum on this device is ${max} (${key}). Remove one first, or ask the user whether to raise ${key} (config_set).`);
242
+ }
243
+ }
244
+
245
+ /** True when available RAM is under the reserve (new heavy work is refused). */
246
+ export function underReserve(cfg, availableBytes) {
247
+ return availableBytes < limits(cfg).reserveMem;
248
+ }
@@ -0,0 +1,130 @@
1
+ // How device tools ask the user for missing details or a yes/no.
2
+ //
3
+ // Two ways, chosen per call (ASK_MODE: auto | elicit | tool):
4
+ // elicit: an MCP elicitation form the client renders. Claude Code renders it
5
+ // only in the terminal on this machine, so a remote user (phone,
6
+ // claude.ai) never sees it and the session sits "waiting on your
7
+ // computer". Used only when the session is local.
8
+ // tool: the tool does nothing and replies with what to ask; the agent asks
9
+ // with its own question tool (AskUserQuestion), which reaches the user
10
+ // wherever they are, and calls again. Confirmations come back with a
11
+ // one-use token bound to the exact arguments, so a "yes" can't be
12
+ // reused for a different action.
13
+ // auto = tool for Remote Control sessions (HD_REMOTE_CONTROL=1), the HTTP
14
+ // server, and clients without elicitation; elicit otherwise.
15
+
16
+ import crypto from 'node:crypto';
17
+
18
+ /** The user declined or cancelled; reported as a plain result, not a failure. */
19
+ export class Cancelled extends Error {}
20
+
21
+ /** Nothing was done yet: the agent must ask the user (message says how) and call again. */
22
+ export class NeedsUser extends Error {}
23
+
24
+ const SECRET = crypto.randomBytes(32);
25
+ const TTL_MS = 10 * 60 * 1000;
26
+ const used = new Map(); // token -> expiry, so each "yes" works once
27
+
28
+ /** Stable JSON of the arguments that define the action (the token itself excluded). */
29
+ function canonical(args) {
30
+ const keys = Object.keys(args || {}).filter((k) => k !== 'confirm_token' && args[k] !== undefined).sort();
31
+ return JSON.stringify(keys.map((k) => [k, args[k]]));
32
+ }
33
+
34
+ function sign(tool, args, exp) {
35
+ return crypto.createHmac('sha256', SECRET).update(`${tool}\n${exp}\n${canonical(args)}`).digest('base64url').slice(0, 22);
36
+ }
37
+
38
+ export function issueToken(tool, args, now = Date.now()) {
39
+ const exp = now + TTL_MS;
40
+ return `${exp.toString(36)}.${sign(tool, args, exp)}`;
41
+ }
42
+
43
+ /** True once for a token issued for exactly this tool + arguments, within its lifetime. */
44
+ export function redeemToken(tool, args, token, now = Date.now()) {
45
+ if (typeof token !== 'string' || !/^[a-z0-9]+\.[\w-]{22}$/.test(token)) return false;
46
+ for (const [t, e] of used) if (e < now) used.delete(t);
47
+ const [e36, mac] = token.split('.');
48
+ const exp = parseInt(e36, 36);
49
+ if (!Number.isFinite(exp) || exp < now || exp > now + TTL_MS) return false;
50
+ const want = sign(tool, args, exp);
51
+ if (want.length !== mac.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(mac))) return false;
52
+ if (used.has(token)) return false;
53
+ used.set(token, exp);
54
+ return true;
55
+ }
56
+
57
+ /** 'elicit' or 'tool' for this call. */
58
+ export function askMode(ctx, server, { transport = 'stdio' } = {}) {
59
+ const want = String(ctx.cfg.ASK_MODE || 'auto');
60
+ const can = !!server.server.getClientCapabilities()?.elicitation;
61
+ if (want === 'tool' || !can) return 'tool';
62
+ if (want === 'elicit') return 'elicit';
63
+ if (ctx.env.HD_REMOTE_CONTROL === '1') return 'tool';
64
+ return transport === 'http' ? 'tool' : 'elicit';
65
+ }
66
+
67
+ const timeoutMs = (ctx) => Math.max(10, Math.min(Number(ctx.cfg.ELICIT_TIMEOUT_SECONDS) || 90, 600)) * 1000;
68
+
69
+ /** Elicit a form; null when the client didn't answer in time (the user is not at this machine). */
70
+ async function elicit(ctx, server, message, properties, required) {
71
+ try {
72
+ const r = await server.server.elicitInput({ mode: 'form', message, requestedSchema: { type: 'object', properties, required } }, { timeout: timeoutMs(ctx) });
73
+ if (r.action !== 'accept') throw new Cancelled(`Cancelled by the user (${r.action}); nothing was changed.`);
74
+ return r.content || {};
75
+ } catch (e) {
76
+ if (e instanceof Cancelled) throw e;
77
+ if (/timed? ?out/i.test(String(e && e.message))) return null;
78
+ throw e;
79
+ }
80
+ }
81
+
82
+ function describeField(name, p) {
83
+ const bits = [p.title || name];
84
+ if (p.description) bits.push(p.description);
85
+ if (p.enum) bits.push(`options: ${p.enum.join(', ')}`);
86
+ if (p.default !== undefined) bits.push(`suggest: ${p.default}`);
87
+ return `- \`${name}\`: ${bits.join('; ')}`;
88
+ }
89
+
90
+ /**
91
+ * Builds ask/confirm for one server. `tool` is the calling tool's name and
92
+ * `args` its arguments (needed for the re-call instructions and the token).
93
+ */
94
+ export function interaction(server, opts = {}) {
95
+ return {
96
+ /** Missing details. Elicit mode returns the answers; tool mode throws NeedsUser. */
97
+ async ask(ctx, tool, args, message, properties, required = Object.keys(properties)) {
98
+ if (askMode(ctx, server, opts) === 'elicit') {
99
+ const got = await elicit(ctx, server, message, properties, required);
100
+ if (got) return got;
101
+ }
102
+ throw new NeedsUser([
103
+ `Nothing was done yet. ${message}: ask the user with AskUserQuestion (offer likely values as options; they can type their own), then call ${tool} again with these arguments added:`,
104
+ ...Object.entries(properties).map(([k, p]) => describeField(k, p)),
105
+ `Keep the arguments already given: ${JSON.stringify(args)}.`,
106
+ ].join('\n'));
107
+ },
108
+
109
+ /** Resolves only on a yes: an accepted form, or a valid confirm_token for exactly these arguments. */
110
+ async confirm(ctx, tool, args, message) {
111
+ if (args.confirm_token !== undefined) {
112
+ if (redeemToken(tool, args, args.confirm_token)) return;
113
+ } else if (askMode(ctx, server, opts) === 'elicit') {
114
+ const got = await elicit(ctx, server, message, { confirm: { type: 'boolean', title: 'Go ahead', default: true } }, ['confirm']);
115
+ if (got) {
116
+ if (!got.confirm) throw new Cancelled('Not confirmed by the user; nothing was changed.');
117
+ return;
118
+ }
119
+ }
120
+ const { confirm_token: _, ...rest } = args;
121
+ const token = issueToken(tool, rest);
122
+ throw new NeedsUser([
123
+ `${args.confirm_token !== undefined ? 'That confirm_token is expired, already used, or for different arguments. ' : ''}Nothing was done yet. This needs the user's OK first.`,
124
+ `Ask the user with AskUserQuestion: "${message}" with the options "Go ahead" and "Cancel".`,
125
+ `If they choose Go ahead, call ${tool} again with exactly these arguments: ${JSON.stringify({ ...rest, confirm_token: token })}`,
126
+ 'If they cancel, do not call it. The token works once, for these arguments only, for 10 minutes.',
127
+ ].join('\n'));
128
+ },
129
+ };
130
+ }