@dreamtree-org/harness-device 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/package.json +1 -1
- package/sh/bin/hd-proc-loop +10 -1
- package/sh/bin/hd-serve-claude +3 -0
- package/sh/bin/hd-tmux-layout +3 -0
- package/sh/bin/hd-watchdog +13 -0
- package/src/capabilities.js +19 -1
- package/src/cleanup.js +195 -0
- package/src/cli.js +54 -10
- package/src/config.js +55 -1
- package/src/container.js +26 -0
- package/src/context.js +4 -1
- package/src/device.js +21 -1
- package/src/doctor.js +10 -0
- package/src/limits.js +248 -0
- package/src/mcp/interact.js +130 -0
- package/src/mcp/server.js +71 -46
- package/src/platform/darwin.js +2 -1
- package/src/platform/linux.js +2 -0
- package/src/providers/claude.js +4 -1
- package/src/resources.js +3 -2
- package/src/serve/cli.js +129 -0
- package/src/serve/http.js +120 -0
- package/src/serve/oauth.js +235 -0
- package/src/serve/scopes.js +37 -0
- package/src/state.js +15 -0
- package/templates/systemd/harness-chromium.service +4 -0
- package/templates/systemd/harness-serve.service +16 -0
- package/templates/systemd/harness-tmux.service +4 -0
package/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
|
|
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
|
+
}
|