@dreamtree-org/harness-device 0.1.2 → 0.1.4
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/CHANGELOG.md +18 -0
- package/README.md +26 -6
- package/package.json +1 -1
- package/sh/bin/hd-gate-hook +6 -0
- package/sh/bin/hd-heal +23 -0
- package/src/capabilities.js +20 -3
- package/src/cli.js +115 -27
- package/src/config.js +68 -0
- package/src/device.js +45 -3
- package/src/install.js +3 -2
- package/src/mcp/server.js +111 -5
- package/src/platform/darwin.js +14 -0
- package/src/platform/linux.js +18 -1
- package/src/providers/claude.js +61 -5
- package/src/resources.js +168 -0
- package/src/upgrade.js +151 -0
package/src/mcp/server.js
CHANGED
|
@@ -9,13 +9,48 @@ import { z } from 'zod';
|
|
|
9
9
|
import { loadContext } from '../context.js';
|
|
10
10
|
import * as device from '../device.js';
|
|
11
11
|
import * as state from '../state.js';
|
|
12
|
+
import * as ngrok from '../ngrok.js';
|
|
12
13
|
import { PKG, sendChildOutputToStderr } from '../util.js';
|
|
14
|
+
import { SETTABLE_KEYS, setConfigValue } from '../config.js';
|
|
15
|
+
import * as resources from '../resources.js';
|
|
16
|
+
import * as upgrader from '../upgrade.js';
|
|
13
17
|
|
|
14
18
|
const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
|
|
15
19
|
const fail = (e) => ({ isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] });
|
|
16
20
|
|
|
17
21
|
const has = (ctx, id) => ctx.caps.some((c) => c.id === id);
|
|
18
22
|
|
|
23
|
+
/** `force`: skip waiting for a critical device (and be refused while it stays critical). */
|
|
24
|
+
const FORCE = { force: z.boolean().optional().describe('skip waiting when the device is critical; refused while critical') };
|
|
25
|
+
|
|
26
|
+
/** Resource guard for new work: waits while CPU/RAM/disk is critical, refuses if it stays so. */
|
|
27
|
+
async function guard(c, a, what) {
|
|
28
|
+
await resources.gate(c, { force: !!a.force, what, waitSeconds: Math.min(Number(c.cfg.RES_WAIT_SECONDS) || 0, 240) });
|
|
29
|
+
}
|
|
30
|
+
|
|
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
|
+
/**
|
|
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.
|
|
38
|
+
*/
|
|
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
|
+
|
|
19
54
|
export function buildServer(env = process.env) {
|
|
20
55
|
const ctx = () => loadContext(env);
|
|
21
56
|
const base = ctx();
|
|
@@ -25,7 +60,8 @@ export function buildServer(env = process.env) {
|
|
|
25
60
|
try {
|
|
26
61
|
return await fn(ctx(), args || {});
|
|
27
62
|
} catch (e) {
|
|
28
|
-
return fail(e);
|
|
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);
|
|
29
65
|
}
|
|
30
66
|
});
|
|
31
67
|
|
|
@@ -39,14 +75,28 @@ export function buildServer(env = process.env) {
|
|
|
39
75
|
async (c) => text(state.listProcs(c)));
|
|
40
76
|
|
|
41
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.',
|
|
42
|
-
{ name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), dir: z.string().describe('absolute working directory'), command: z.string().describe('one shell line, e.g. "npm run dev -- --port 5173"') },
|
|
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 },
|
|
43
79
|
async (c, a) => {
|
|
80
|
+
await guard(c, a, `starting process ${a.name}`);
|
|
81
|
+
if (!a.dir || !a.command) {
|
|
82
|
+
const first = c.projects[0];
|
|
83
|
+
const got = await ask(server, `Details for the long-running process "${a.name}"`, {
|
|
84
|
+
...(a.dir ? {} : { dir: { type: 'string', title: 'Working directory', description: 'Absolute path, usually the project folder', ...(first ? { default: first.dir } : {}) } }),
|
|
85
|
+
...(a.command ? {} : { command: { type: 'string', title: 'Command', description: 'One shell line, e.g. npm run dev -- --port 5173' } }),
|
|
86
|
+
});
|
|
87
|
+
a = { ...a, ...got };
|
|
88
|
+
if (typeof a.dir !== 'string' || typeof a.command !== 'string' || !a.dir || !a.command) throw new Error('Both a directory and a command are needed');
|
|
89
|
+
}
|
|
44
90
|
state.addProc(c, a.name, a.dir, a.command);
|
|
45
91
|
return text(`proc ${a.name} registered; window proc-${a.name}; logs: logs tool with target "proc-${a.name}"`);
|
|
46
92
|
});
|
|
47
93
|
|
|
48
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}$/) },
|
|
49
|
-
async (c, a) => {
|
|
95
|
+
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
|
+
state.removeProc(c, a.name);
|
|
98
|
+
return text(`proc ${a.name} removed`);
|
|
99
|
+
});
|
|
50
100
|
|
|
51
101
|
tool('viewers', 'URLs where the user watches live progress (noVNC display, read-only tmux, Playwright UI) and the SSH tunnel command to reach them.', {},
|
|
52
102
|
async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
|
|
@@ -80,14 +130,17 @@ export function buildServer(env = process.env) {
|
|
|
80
130
|
dir: z.string().describe('absolute path of the project (folder with playwright.config)'),
|
|
81
131
|
args: z.array(z.string()).optional().describe('extra playwright test args, e.g. ["tests/login.spec.ts", "--project=chromium"]'),
|
|
82
132
|
timeoutMinutes: z.number().int().min(1).max(120).optional(),
|
|
133
|
+
...FORCE,
|
|
83
134
|
},
|
|
84
135
|
async (c, a) => {
|
|
136
|
+
await guard(c, a, 'a test run');
|
|
85
137
|
if (!path.isAbsolute(a.dir) || !fs.existsSync(a.dir)) throw new Error(`Not an existing absolute path: ${a.dir}`);
|
|
86
138
|
return text(await device.runTestsLive(c, a.dir, a.args || [], (a.timeoutMinutes || 15) * 60000));
|
|
87
139
|
});
|
|
88
140
|
tool('playwright_ui', 'Open (or stop) Playwright UI mode for a project, for the user to watch and re-run tests interactively.',
|
|
89
|
-
{ dir: z.string().optional(), stop: z.boolean().optional() },
|
|
141
|
+
{ dir: z.string().optional(), stop: z.boolean().optional(), ...FORCE },
|
|
90
142
|
async (c, a) => {
|
|
143
|
+
if (!a.stop) await guard(c, a, 'Playwright UI');
|
|
91
144
|
if (!a.stop && (!a.dir || !path.isAbsolute(a.dir) || !fs.existsSync(a.dir))) throw new Error('dir (an existing absolute path) is required unless stop is true');
|
|
92
145
|
return text(device.pwUi(c, a.dir, !!a.stop) + `\nURL: ${device.viewers(c.cfg, c.platform).playwrightUi}`);
|
|
93
146
|
});
|
|
@@ -99,10 +152,63 @@ export function buildServer(env = process.env) {
|
|
|
99
152
|
}
|
|
100
153
|
|
|
101
154
|
if (has(base, 'ngrok')) {
|
|
102
|
-
tool('ngrok_status', 'Public ngrok URLs currently open on this device
|
|
155
|
+
tool('ngrok_status', 'Public ngrok URLs currently open on this device.', {},
|
|
103
156
|
async () => text(await device.ngrokStatus()));
|
|
157
|
+
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
|
+
{ 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) => {
|
|
160
|
+
let tunnels = a.tunnels || [];
|
|
161
|
+
let ports = a.ports || [];
|
|
162
|
+
if (!tunnels.length && !ports.length) {
|
|
163
|
+
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?', {
|
|
165
|
+
tunnel: { type: 'string', title: 'Tunnel', enum: [...names, 'app port'], description: 'An existing tunnel, or "app port" for a local server' },
|
|
166
|
+
port: { type: 'integer', title: 'App port', minimum: 1, maximum: 65535, description: 'Only for "app port", e.g. 3000' },
|
|
167
|
+
}, ['tunnel']);
|
|
168
|
+
if (got.tunnel === 'app port') {
|
|
169
|
+
if (!got.port) throw new Error('No port given');
|
|
170
|
+
ports = [got.port];
|
|
171
|
+
} else tunnels = [got.tunnel];
|
|
172
|
+
}
|
|
173
|
+
return text(await device.ngrokUp(c, { tunnels, ports }));
|
|
174
|
+
});
|
|
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?');
|
|
178
|
+
c.platform.ngrokDown(c);
|
|
179
|
+
return text('ngrok tunnels closed');
|
|
180
|
+
});
|
|
104
181
|
}
|
|
105
182
|
|
|
183
|
+
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)));
|
|
185
|
+
|
|
186
|
+
tool('upgrade', 'Check for a newer harness-device on npm, or upgrade to it (the user approves this call). Upgrades run in the background without stopping sessions or unchanged services; the device also does this on its own per AUTO_UPGRADE. check=true only reports.',
|
|
187
|
+
{ check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional() },
|
|
188
|
+
async (c, a) => {
|
|
189
|
+
const chk = await upgrader.check(c, { to: a.version });
|
|
190
|
+
if (a.check || !chk.available || chk.source !== 'npm') return text(chk);
|
|
191
|
+
if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `Upgrade harness-device ${chk.current} → ${chk.latest} now? Sessions keep running; only services whose definitions changed restart.`);
|
|
192
|
+
c.platform.spawnDetached(c, 'upgrade', [path.join(c.paths.bin, 'harness-device'), 'upgrade', '--to', chk.latest], path.join(c.paths.logs, 'upgrade.log'));
|
|
193
|
+
return text(`Upgrading ${chk.current} → ${chk.latest} in the background. Follow it with the logs tool, target "upgrade"; this session gets the new tools when it next restarts.`);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
tool('config_get', `Current device settings that can be changed with config_set: ${Object.keys(SETTABLE_KEYS).join(', ')}.`, {},
|
|
197
|
+
async (c) => text(Object.fromEntries(Object.keys(SETTABLE_KEYS).map((k) => [k, c.cfg[k] ?? '']))));
|
|
198
|
+
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.`,
|
|
199
|
+
{ key: z.enum(Object.keys(SETTABLE_KEYS)).optional(), value: z.string().max(200).optional() },
|
|
200
|
+
async (c, a) => {
|
|
201
|
+
if (!a.key || a.value === undefined) {
|
|
202
|
+
const got = await ask(server, 'Change a device setting', {
|
|
203
|
+
...(a.key ? {} : { key: { type: 'string', title: 'Setting', enum: Object.keys(SETTABLE_KEYS), description: Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k}: ${d}`).join('; ') } }),
|
|
204
|
+
value: { type: 'string', title: 'Value', maxLength: 200, ...(a.key ? { description: SETTABLE_KEYS[a.key] } : {}) },
|
|
205
|
+
});
|
|
206
|
+
a = { ...a, ...got };
|
|
207
|
+
if (!Object.prototype.hasOwnProperty.call(SETTABLE_KEYS, a.key)) throw new Error(`Unknown setting ${a.key}`);
|
|
208
|
+
}
|
|
209
|
+
return text(setConfigValue(a.key, String(a.value ?? ''), env));
|
|
210
|
+
});
|
|
211
|
+
|
|
106
212
|
return server;
|
|
107
213
|
}
|
|
108
214
|
|
package/src/platform/darwin.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import os from 'node:os';
|
|
9
9
|
import path from 'node:path';
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
10
11
|
import { PKG_ROOT, run, capture, ok, which, writeFile, color } from '../util.js';
|
|
11
12
|
|
|
12
13
|
export const id = 'darwin';
|
|
@@ -232,3 +233,16 @@ export function viewers(cfg) {
|
|
|
232
233
|
tunnelPorts: [5900, cfg.TTYD_PORT, cfg.PW_UI_PORT],
|
|
233
234
|
};
|
|
234
235
|
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Run a harness-device command in its own process group, so reloading a
|
|
239
|
+
* launchd job (heal included) can't stop it.
|
|
240
|
+
*/
|
|
241
|
+
export function spawnDetached(ctx, name, args, logFile) {
|
|
242
|
+
fs.mkdirSync(path.dirname(logFile), { recursive: true });
|
|
243
|
+
const fd = fs.openSync(logFile, 'a');
|
|
244
|
+
const child = spawn(args[0], args.slice(1), { env: ctx.env, detached: true, stdio: ['ignore', fd, fd] });
|
|
245
|
+
child.unref();
|
|
246
|
+
fs.closeSync(fd);
|
|
247
|
+
return child.pid;
|
|
248
|
+
}
|
package/src/platform/linux.js
CHANGED
|
@@ -49,9 +49,12 @@ export function renderServices(ctx, detect = true) {
|
|
|
49
49
|
const sysd = (args, env, opts = {}) => run('systemctl', ['--user', ...args], { env, ...opts });
|
|
50
50
|
|
|
51
51
|
/** Write units, drop stale ones, enable at boot, start; never restart tmux (live sessions). */
|
|
52
|
-
export function activate(ctx, files, { dryRun }) {
|
|
52
|
+
export function activate(ctx, files, { dryRun, graceful = false }) {
|
|
53
53
|
const env = userEnv(ctx.env);
|
|
54
54
|
const dir = serviceDir(env);
|
|
55
|
+
// Graceful (upgrades): restart only services whose unit file changed; the rest
|
|
56
|
+
// pick up new scripts at their next restart.
|
|
57
|
+
const changed = new Set(Object.keys(files).filter((n) => !fs.existsSync(path.join(dir, n)) || fs.readFileSync(path.join(dir, n), 'utf8') !== files[n]));
|
|
55
58
|
const stale = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^harness[.-]/.test(f) && !(f in files)) : [];
|
|
56
59
|
for (const f of stale) {
|
|
57
60
|
sysd(['disable', '--now', f], env, { dryRun, allowFail: true });
|
|
@@ -63,6 +66,9 @@ export function activate(ctx, files, { dryRun }) {
|
|
|
63
66
|
sysd(['enable', 'harness.target', 'harness-heal.timer'], env, { dryRun });
|
|
64
67
|
for (const u of ctx.units) {
|
|
65
68
|
if (u === 'harness-tmux') continue;
|
|
69
|
+
if (graceful && !changed.has(unitName(u))) continue;
|
|
70
|
+
// Never restart heal from inside an upgrade it may be running; the timer starts it next time.
|
|
71
|
+
if (graceful && u === 'harness-heal') continue;
|
|
66
72
|
sysd([u === 'harness-heal' ? 'restart' : 'try-restart', unitName(u)], env, { dryRun, allowFail: true });
|
|
67
73
|
}
|
|
68
74
|
sysd(['start', 'harness.target'], env, { dryRun });
|
|
@@ -140,3 +146,14 @@ export function viewers(cfg) {
|
|
|
140
146
|
tunnelPorts: [cfg.NOVNC_PORT, cfg.TTYD_PORT, cfg.PW_UI_PORT],
|
|
141
147
|
};
|
|
142
148
|
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Run a harness-device command outside every harness service (a transient
|
|
152
|
+
* user unit), so reloading those services, heal included, can't stop it.
|
|
153
|
+
*/
|
|
154
|
+
export function spawnDetached(ctx, name, args, logFile) {
|
|
155
|
+
const env = userEnv(ctx.env);
|
|
156
|
+
const setenv = ['PATH', 'HOME', 'HARNESS_DEVICE_HOME', 'CLAUDE_CONFIG_DIR'].filter((k) => env[k]).map((k) => `--setenv=${k}=${env[k]}`);
|
|
157
|
+
return run('systemd-run', ['--user', '--quiet', '--collect', `--unit=harness-${name}-${Date.now()}`, ...setenv,
|
|
158
|
+
'/bin/sh', '-c', 'exec "$0" "$@" >> "' + logFile.replace(/"/g, '') + '" 2>&1', ...args], { env, allowFail: true });
|
|
159
|
+
}
|
package/src/providers/claude.js
CHANGED
|
@@ -49,6 +49,25 @@ export function removeBlock(text) {
|
|
|
49
49
|
* themselves are never removed or recorded as ours.
|
|
50
50
|
* Returns { settings, added } where added is the new record to keep.
|
|
51
51
|
*/
|
|
52
|
+
const GATE_HOOK = 'hd-gate-hook';
|
|
53
|
+
const isOurHook = (entry) => (entry.hooks || []).some((h) => String(h.command || '').endsWith(GATE_HOOK));
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Put the device's resource guard on Bash (PreToolUse), or take it off.
|
|
57
|
+
* Only an entry whose command is our hd-gate-hook is ever touched.
|
|
58
|
+
*/
|
|
59
|
+
export function mergeGateHook(settings, { bin, on, timeoutSeconds = 360 }) {
|
|
60
|
+
const s = JSON.parse(JSON.stringify(settings || {}));
|
|
61
|
+
const pre = ((s.hooks && s.hooks.PreToolUse) || []).filter((e) => !isOurHook(e));
|
|
62
|
+
if (on) pre.push({ matcher: 'Bash', hooks: [{ type: 'command', command: path.join(bin, GATE_HOOK), timeout: timeoutSeconds }] });
|
|
63
|
+
if (pre.length) s.hooks = { ...(s.hooks || {}), PreToolUse: pre };
|
|
64
|
+
else if (s.hooks) {
|
|
65
|
+
delete s.hooks.PreToolUse;
|
|
66
|
+
if (!Object.keys(s.hooks).length) delete s.hooks;
|
|
67
|
+
}
|
|
68
|
+
return s;
|
|
69
|
+
}
|
|
70
|
+
|
|
52
71
|
export function mergePermissions(settings, { allow = [], deny = [] }, prev = { allow: [], deny: [] }) {
|
|
53
72
|
const s = JSON.parse(JSON.stringify(settings || {}));
|
|
54
73
|
s.permissions = s.permissions || {};
|
|
@@ -100,6 +119,23 @@ function readJson(file, fallback) {
|
|
|
100
119
|
}
|
|
101
120
|
}
|
|
102
121
|
|
|
122
|
+
/**
|
|
123
|
+
* How this provider lets the agent ask the remote user with interactive UI.
|
|
124
|
+
* Every provider fills the same shape; the skill/instructions take guidance()
|
|
125
|
+
* from here, and the device's MCP tools use elicitation when the client has it.
|
|
126
|
+
*/
|
|
127
|
+
export const interaction = {
|
|
128
|
+
askTool: 'AskUserQuestion',
|
|
129
|
+
supportsElicitation: true,
|
|
130
|
+
guidance: () => `## Asking the user
|
|
131
|
+
The user usually drives this session remotely (phone, claude.ai) and answers by tapping, so ask with interactive prompts, not prose:
|
|
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.
|
|
134
|
+
- 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
|
+
- Never tell the user to run commands on the machine. Ask with options, then do it yourself through the tools.
|
|
136
|
+
- 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.`,
|
|
137
|
+
};
|
|
138
|
+
|
|
103
139
|
export function renderSkill({ cfg, caps, projects, platform }) {
|
|
104
140
|
const head = `---
|
|
105
141
|
name: harness-device
|
|
@@ -113,7 +149,7 @@ This machine is a harness device: a dev environment kept running for remote agen
|
|
|
113
149
|
Projects on this device: ${projects.map((p) => `\`${p.name}\` (${p.dir})`).join(', ') || 'none yet'}.
|
|
114
150
|
Device controls are available both as the \`harness-device\` MCP tools and as the \`harness-device\` CLI.
|
|
115
151
|
`;
|
|
116
|
-
return head + '\n' + caps.map((c) => (c.docs ? c.docs(cfg, platform) : '')).filter(Boolean).join('\n\n') + '\n';
|
|
152
|
+
return head + '\n' + [interaction.guidance(cfg), ...caps.map((c) => (c.docs ? c.docs(cfg, platform) : ''))].filter(Boolean).join('\n\n') + '\n';
|
|
117
153
|
}
|
|
118
154
|
|
|
119
155
|
export function renderClaudeMd({ cfg }) {
|
|
@@ -130,17 +166,30 @@ export function userMcpServers(env) {
|
|
|
130
166
|
// harness-device MCP tools that only read, or restart the browser. proc_add,
|
|
131
167
|
// proc_remove, restart_service and playwright_ui still ask: they start or stop things.
|
|
132
168
|
export const HARNESS_TOOLS_ALLOWED = ['device_status', 'sessions', 'proc_list', 'viewers', 'disk_usage', 'logs',
|
|
133
|
-
'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status'].map((t) => `mcp__harness-device__${t}`);
|
|
169
|
+
'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status', 'config_get', 'resources'].map((t) => `mcp__harness-device__${t}`);
|
|
134
170
|
|
|
135
171
|
/**
|
|
136
172
|
* A Read() rule for an absolute path. In Claude Code rules `/x` is relative to
|
|
137
173
|
* the settings file; `~/x` is under home and `//x` is absolute.
|
|
138
174
|
*/
|
|
139
175
|
export function readRule(abs, home) {
|
|
176
|
+
return pathRule('Read', abs, home);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** A path rule (Read, Edit) for an absolute path; see readRule. */
|
|
180
|
+
export function pathRule(tool, abs, home) {
|
|
140
181
|
const rel = path.relative(home, abs);
|
|
141
|
-
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ?
|
|
182
|
+
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? `${tool}(~/${rel})` : `${tool}(/${abs})`;
|
|
142
183
|
}
|
|
143
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Commands that change the device's own install. A session changes the device
|
|
187
|
+
* only through harness-device tools the user approves there (config_set,
|
|
188
|
+
* ngrok_up, proc_add, ...), never by hand.
|
|
189
|
+
*/
|
|
190
|
+
export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-device install:*)',
|
|
191
|
+
'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)'];
|
|
192
|
+
|
|
144
193
|
/**
|
|
145
194
|
* Wire everything into Claude Code. ctx: { cfg, caps, projects, paths, env, dryRun, mcpServers }
|
|
146
195
|
*/
|
|
@@ -183,8 +232,15 @@ export function apply(ctx) {
|
|
|
183
232
|
readRule(path.join(paths.home, 'secrets.env'), home),
|
|
184
233
|
readRule(path.join(paths.home, 'ngrok*'), home),
|
|
185
234
|
readRule(path.join(home, '.ssh', '**'), home),
|
|
235
|
+
// The Edit rule covers every file-writing tool: the device home changes only through harness-device.
|
|
236
|
+
pathRule('Edit', path.join(paths.home, '**'), home),
|
|
237
|
+
...DEVICE_ADMIN_DENY,
|
|
186
238
|
]))];
|
|
187
|
-
const
|
|
239
|
+
const merged = mergePermissions(readJson(f.settings, {}), { allow, deny }, prev);
|
|
240
|
+
const added = merged.added;
|
|
241
|
+
// Resource guard on the agent's shell commands (waits while the device is critical).
|
|
242
|
+
const settings = mergeGateHook(merged.settings, { bin: paths.bin, on: String(ctx.cfg.RESOURCE_GUARD || 'on') !== 'off',
|
|
243
|
+
timeoutSeconds: Math.min(Number(ctx.cfg.RES_WAIT_SECONDS) || 300, 540) + 60 });
|
|
188
244
|
// Restores resume conversations from their transcripts, so Claude Code
|
|
189
245
|
// must not clean them up early (its default is 30 days).
|
|
190
246
|
const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
|
|
@@ -203,7 +259,7 @@ export function remove(ctx) {
|
|
|
203
259
|
if (fs.existsSync(f.claudeMd)) writeFile(f.claudeMd, removeBlock(fs.readFileSync(f.claudeMd, 'utf8')), { dryRun });
|
|
204
260
|
const stateFile = path.join(paths.home, 'claude-permissions.json');
|
|
205
261
|
const prev = readJson(stateFile, { allow: [], deny: [] });
|
|
206
|
-
if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(unmergePermissions(readJson(f.settings, {}), prev), null, 2) + '\n', { dryRun });
|
|
262
|
+
if (fs.existsSync(f.settings)) writeFile(f.settings, JSON.stringify(mergeGateHook(unmergePermissions(readJson(f.settings, {}), prev), { on: false }), null, 2) + '\n', { dryRun });
|
|
207
263
|
if (!dryRun) fs.rmSync(stateFile, { force: true });
|
|
208
264
|
}
|
|
209
265
|
|
package/src/resources.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Resource awareness: CPU, RAM and disk (persistent storage) on this device.
|
|
2
|
+
// New work from a session (registered processes, test runs, heavy shell
|
|
3
|
+
// commands through the provider's hook) passes through gate(): when the device
|
|
4
|
+
// is critical it waits for it to recover; a forced request is refused instead
|
|
5
|
+
// while it stays critical, never run on top of it.
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import { capture } from './util.js';
|
|
10
|
+
|
|
11
|
+
const GiB = 1024 ** 3;
|
|
12
|
+
const RANK = { ok: 0, high: 1, critical: 2 };
|
|
13
|
+
const worst = (...ls) => ls.reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'ok');
|
|
14
|
+
const num = (v, d) => (Number.isFinite(Number(v)) && String(v).trim() !== '' ? Number(v) : d);
|
|
15
|
+
|
|
16
|
+
/** Thresholds from config (percent values). */
|
|
17
|
+
export function thresholds(cfg = {}) {
|
|
18
|
+
return {
|
|
19
|
+
cpuCritical: num(cfg.RES_CPU_CRITICAL, 95), // busy % (and at least one runnable task per core)
|
|
20
|
+
cpuHigh: Math.min(num(cfg.RES_CPU_CRITICAL, 95), 85),
|
|
21
|
+
memCritical: num(cfg.RES_MEM_CRITICAL, 5), // % of RAM still available
|
|
22
|
+
memHigh: Math.max(num(cfg.RES_MEM_CRITICAL, 5), 12),
|
|
23
|
+
diskCritical: num(cfg.RES_DISK_CRITICAL, 3), // % free on a device or project filesystem
|
|
24
|
+
diskHigh: Math.max(num(cfg.RES_DISK_CRITICAL, 3), 10),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Busy % of all cores over `ms` (from os.cpus() tick counters). */
|
|
29
|
+
async function cpuBusy(ms) {
|
|
30
|
+
const snap = () => os.cpus().reduce((a, c) => {
|
|
31
|
+
const t = Object.values(c.times).reduce((x, y) => x + y, 0);
|
|
32
|
+
return { idle: a.idle + c.times.idle, total: a.total + t };
|
|
33
|
+
}, { idle: 0, total: 0 });
|
|
34
|
+
const a = snap();
|
|
35
|
+
await new Promise((r) => setTimeout(r, ms));
|
|
36
|
+
const b = snap();
|
|
37
|
+
const total = b.total - a.total;
|
|
38
|
+
return total > 0 ? Math.round(100 * (1 - (b.idle - a.idle) / total)) : 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** RAM: total and available bytes (what can be used without swapping). */
|
|
42
|
+
export function memory(platform = process.platform, read = fs.readFileSync, run = capture) {
|
|
43
|
+
const total = os.totalmem();
|
|
44
|
+
if (platform === 'linux') {
|
|
45
|
+
try {
|
|
46
|
+
const m = Object.fromEntries(read('/proc/meminfo', 'utf8').split('\n').map((l) => l.match(/^(\w+):\s+(\d+)/)).filter(Boolean).map((x) => [x[1], Number(x[2]) * 1024]));
|
|
47
|
+
if (m.MemAvailable !== undefined) return { total: m.MemTotal || total, available: m.MemAvailable };
|
|
48
|
+
} catch { /* fall through */ }
|
|
49
|
+
}
|
|
50
|
+
if (platform === 'darwin') {
|
|
51
|
+
// The kernel's own "memory available" level, the figure Activity Monitor's pressure is based on.
|
|
52
|
+
const level = Number(run('sysctl', ['-n', 'kern.memorystatus_level'], { timeout: 3000 }));
|
|
53
|
+
if (Number.isFinite(level) && level > 0 && level <= 100) return { total, available: Math.round((total * level) / 100) };
|
|
54
|
+
const vm = run('vm_stat', [], { timeout: 3000 });
|
|
55
|
+
const page = Number((vm.match(/page size of (\d+)/) || [])[1] || 4096);
|
|
56
|
+
const pages = (k) => Number((vm.match(new RegExp(`Pages ${k}:\\s+(\\d+)`)) || [])[1] || 0);
|
|
57
|
+
if (vm) return { total, available: (pages('free') + pages('inactive') + pages('speculative') + pages('purgeable')) * page };
|
|
58
|
+
}
|
|
59
|
+
return { total, available: os.freemem() };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Disk: one entry per filesystem holding any of `dirs`. */
|
|
63
|
+
export function disks(dirs, run = capture) {
|
|
64
|
+
const existing = [...new Set(dirs.filter((d) => d && fs.existsSync(d)))];
|
|
65
|
+
if (!existing.length) return [];
|
|
66
|
+
const out = run('df', ['-Pk', ...existing], { timeout: 5000 });
|
|
67
|
+
const seen = new Map();
|
|
68
|
+
out.split('\n').slice(1).forEach((line, i) => {
|
|
69
|
+
const f = line.trim().split(/\s+/);
|
|
70
|
+
if (f.length < 6) return;
|
|
71
|
+
const total = Number(f[1]) * 1024;
|
|
72
|
+
const free = Number(f[3]) * 1024;
|
|
73
|
+
const mount = f.slice(5).join(' ');
|
|
74
|
+
if (!seen.has(mount)) seen.set(mount, { mount, total, free, freePct: total ? Math.round((100 * free) / total) : 100, dirs: [] });
|
|
75
|
+
if (existing[i]) seen.get(mount).dirs.push(existing[i]);
|
|
76
|
+
});
|
|
77
|
+
return [...seen.values()];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* One reading of the device. `quick` skips the CPU sample unless the load
|
|
82
|
+
* average already says the CPUs are saturated (keeps the shell hook fast).
|
|
83
|
+
*/
|
|
84
|
+
export async function sample(ctx, { quick = false, sampleMs = 400 } = {}) {
|
|
85
|
+
const t = thresholds(ctx.cfg);
|
|
86
|
+
const cores = os.cpus().length || 1;
|
|
87
|
+
const load1 = os.loadavg()[0];
|
|
88
|
+
const loadPct = Math.round((100 * load1) / cores);
|
|
89
|
+
const busy = quick && loadPct < 100 ? null : await cpuBusy(sampleMs);
|
|
90
|
+
const cpuLevel = busy !== null && busy >= t.cpuCritical && loadPct >= 100 ? 'critical'
|
|
91
|
+
: (busy ?? loadPct) >= t.cpuHigh ? 'high' : 'ok';
|
|
92
|
+
|
|
93
|
+
const m = memory();
|
|
94
|
+
const memPct = m.total ? Math.round((100 * m.available) / m.total) : 100;
|
|
95
|
+
const memLevel = memPct <= t.memCritical ? 'critical' : memPct <= t.memHigh ? 'high' : 'ok';
|
|
96
|
+
|
|
97
|
+
const d = disks([ctx.paths.home, ...(ctx.projects || []).map((p) => p.dir)]);
|
|
98
|
+
for (const x of d) {
|
|
99
|
+
x.level = x.freePct <= t.diskCritical || x.free < 1 * GiB ? 'critical' : x.freePct <= t.diskHigh || x.free < 5 * GiB ? 'high' : 'ok';
|
|
100
|
+
}
|
|
101
|
+
const diskLevel = worst(...d.map((x) => x.level));
|
|
102
|
+
|
|
103
|
+
const level = worst(cpuLevel, memLevel, diskLevel);
|
|
104
|
+
const reasons = [];
|
|
105
|
+
if (cpuLevel !== 'ok') reasons.push(`CPU ${busy ?? loadPct}% busy (load ${load1.toFixed(2)} on ${cores} cores)`);
|
|
106
|
+
if (memLevel !== 'ok') reasons.push(`RAM ${memPct}% available (${(m.available / GiB).toFixed(1)} of ${(m.total / GiB).toFixed(1)} GiB)`);
|
|
107
|
+
for (const x of d) if (x.level !== 'ok') reasons.push(`disk ${x.mount} ${x.freePct}% free (${(x.free / GiB).toFixed(1)} GiB)`);
|
|
108
|
+
return {
|
|
109
|
+
level,
|
|
110
|
+
reasons,
|
|
111
|
+
cpu: { level: cpuLevel, busyPct: busy, loadPct, load1: Number(load1.toFixed(2)), cores },
|
|
112
|
+
memory: { level: memLevel, availablePct: memPct, availableGiB: Number((m.available / GiB).toFixed(2)), totalGiB: Number((m.total / GiB).toFixed(2)) },
|
|
113
|
+
disk: { level: diskLevel, filesystems: d.map((x) => ({ mount: x.mount, level: x.level, freePct: x.freePct, freeGiB: Number((x.free / GiB).toFixed(1)), dirs: x.dirs })) },
|
|
114
|
+
thresholds: t,
|
|
115
|
+
at: new Date().toISOString(),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function summary(s) {
|
|
120
|
+
const disk = s.disk.filesystems.map((x) => `${x.mount} ${x.freePct}% free`).join(', ') || 'n/a';
|
|
121
|
+
return `${s.level.toUpperCase()} · CPU ${s.cpu.busyPct ?? s.cpu.loadPct}% (load ${s.cpu.load1}/${s.cpu.cores}) · RAM ${s.memory.availablePct}% available · disk ${disk}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export class ResourceDenied extends Error {
|
|
125
|
+
constructor(msg, s) { super(msg); this.sample = s; }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Let new work start only when the device can take it.
|
|
130
|
+
* ok / high → go (high is reported).
|
|
131
|
+
* critical → wait up to waitSeconds for it to recover, then refuse;
|
|
132
|
+
* critical + force → refused at once (forcing never overrides a critical device).
|
|
133
|
+
* RESOURCE_GUARD=off turns the gate off.
|
|
134
|
+
*/
|
|
135
|
+
export async function gate(ctx, { force = false, waitSeconds, what = 'this', quick = false, poll = 5, onWait } = {}) {
|
|
136
|
+
if (String(ctx.cfg.RESOURCE_GUARD || 'on') === 'off') return { allowed: true, level: 'unchecked', waited: 0 };
|
|
137
|
+
const wait = waitSeconds ?? num(ctx.cfg.RES_WAIT_SECONDS, 300);
|
|
138
|
+
let s = await sample(ctx, { quick });
|
|
139
|
+
if (s.level !== 'critical') return { allowed: true, level: s.level, waited: 0, reasons: s.reasons };
|
|
140
|
+
if (force) {
|
|
141
|
+
throw new ResourceDenied(`Refused ${what}: the device is critical (${s.reasons.join('; ')}). Forcing is not allowed while it is critical; free resources first (stop a process, prune Docker, clear disk) or let it wait.`, s);
|
|
142
|
+
}
|
|
143
|
+
const start = Date.now();
|
|
144
|
+
while ((Date.now() - start) / 1000 < wait) {
|
|
145
|
+
if (onWait) onWait(s, Math.round((Date.now() - start) / 1000));
|
|
146
|
+
await new Promise((r) => setTimeout(r, poll * 1000));
|
|
147
|
+
s = await sample(ctx, { quick });
|
|
148
|
+
if (s.level !== 'critical') return { allowed: true, level: s.level, waited: Math.round((Date.now() - start) / 1000), reasons: s.reasons };
|
|
149
|
+
}
|
|
150
|
+
throw new ResourceDenied(`Waited ${wait}s for the device to recover before ${what}, but it is still critical (${s.reasons.join('; ')}). Try again later, or free resources first.`, s);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Shell commands that only look or free resources never wait (checking and
|
|
154
|
+
// fixing a critical device must stay possible).
|
|
155
|
+
const LIGHT = [
|
|
156
|
+
/^(ps|top|htop|free|df|du|uptime|vm_stat|sysctl|iostat|vmstat|nproc|kill|pkill|killall|ls|pwd|cat|head|tail|less|wc|grep|rg|find|echo|printf|which|type|stat|date|env|id|whoami|rm|true)\b/,
|
|
157
|
+
/^git (status|log|diff|show|branch|remote|stash list)\b/,
|
|
158
|
+
/^harness-device (status|logs|events|resources|gate|doctor|proc (list|rm)|session list|ngrok (status|down)|config get|tunnel)\b/,
|
|
159
|
+
/^docker (ps|stop|kill|rm|rmi|logs|stats|system (df|prune)|image (ls|prune)|container (ls|prune)|volume (ls|prune)|builder prune)\b/,
|
|
160
|
+
/^tmux (ls|list-\w+|kill-window|display-message|capture-pane|has-session)\b/,
|
|
161
|
+
/^(npm|pnpm|yarn) cache (clean|verify)\b/,
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
/** True when every part of a shell command line is light. */
|
|
165
|
+
export function isLightCommand(cmd) {
|
|
166
|
+
const parts = String(cmd || '').split(/&&|\|\||;|\||\n/).map((x) => x.trim().replace(/^(\w+=\S*\s+)+/, '').replace(/^(sudo|command|exec|time|nice(\s+-n\s*\d+)?)\s+/, '')).filter(Boolean);
|
|
167
|
+
return parts.length > 0 && parts.every((p) => LIGHT.some((re) => re.test(p)));
|
|
168
|
+
}
|