@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/src/mcp/server.js CHANGED
@@ -14,54 +14,54 @@ import { PKG, sendChildOutputToStderr, capture } from '../util.js';
14
14
  import { SETTABLE_KEYS, setConfigValue } from '../config.js';
15
15
  import * as resources from '../resources.js';
16
16
  import * as upgrader from '../upgrade.js';
17
+ import * as cleanup from '../cleanup.js';
18
+ import * as limits from '../limits.js';
19
+ import { Cancelled, NeedsUser, interaction } from './interact.js';
17
20
 
18
21
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
19
22
  const fail = (e) => ({ isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] });
20
23
 
21
24
  const has = (ctx, id) => ctx.caps.some((c) => c.id === id);
22
25
 
26
+ /** Present on every tool that confirms first; see ./interact.js. */
27
+ const CONFIRM = { confirm_token: z.string().max(64).optional().describe('the token from this tool\'s previous reply, after the user said Go ahead through AskUserQuestion') };
28
+
23
29
  /** `force`: skip waiting for a critical device (and be refused while it stays critical). */
24
30
  const FORCE = { force: z.boolean().optional().describe('skip waiting when the device is critical; refused while critical') };
25
31
 
26
32
  /** Resource guard for new work: waits while CPU/RAM/disk is critical, refuses if it stays so. */
27
33
  async function guard(c, a, what) {
28
34
  await resources.gate(c, { force: !!a.force, what, waitSeconds: Math.min(Number(c.cfg.RES_WAIT_SECONDS) || 0, 240) });
35
+ // The RAM reserve is for the OS, Docker and other apps: heavy new work never eats into it.
36
+ const m = resources.memory();
37
+ if (String(c.cfg.RESOURCE_GUARD || 'on') !== 'off' && limits.underReserve(c.cfg, m.available)) {
38
+ const s = await resources.sample(c, { quick: true });
39
+ throw new resources.ResourceDenied(`Refused ${what}: only ${limits.humanMem(m.available)} of RAM is available, under the ${limits.humanMem(limits.limits(c.cfg).reserveMem)} kept free for the OS and other apps (RES_RESERVE_MEM). Free memory first (stop a process, close the browser's tabs) or ask the user.`, s);
40
+ }
29
41
  }
30
42
 
31
- /** Thrown when the user declines or cancels a form; reported as a plain result, not a failure. */
32
- class Cancelled extends Error {}
33
-
34
43
  /**
35
- * Ask the user for missing details with an MCP elicitation form (rendered by
36
- * the client: a dialog or card the remote user fills in). Without client
37
- * support it fails with the field names, so the agent asks with its own UI.
44
+ * opts.transport: 'stdio' (a local child of the agent) or 'http' (`serve`);
45
+ * it decides how the tools ask the user (see ./interact.js).
46
+ * opts.allow(name): register only the tools it accepts (`serve` scopes).
38
47
  */
39
- async function ask(server, message, properties, required = Object.keys(properties)) {
40
- if (!server.server.getClientCapabilities()?.elicitation) {
41
- throw new Error(`Missing: ${Object.keys(properties).join(', ')}. Ask the user (with your interactive question tool) and call again with them.`);
42
- }
43
- const r = await server.server.elicitInput({ mode: 'form', message, requestedSchema: { type: 'object', properties, required } });
44
- if (r.action !== 'accept') throw new Cancelled(`Cancelled by the user (${r.action}); nothing was changed.`);
45
- return r.content || {};
46
- }
47
-
48
- /** A yes/no confirmation form; resolves only on yes. */
49
- async function confirm(server, message) {
50
- const a = await ask(server, message, { confirm: { type: 'boolean', title: 'Go ahead', default: true } });
51
- if (!a.confirm) throw new Cancelled('Not confirmed by the user; nothing was changed.');
52
- }
53
-
54
- export function buildServer(env = process.env) {
48
+ export function buildServer(env = process.env, opts = {}) {
55
49
  const ctx = () => loadContext(env);
56
50
  const base = ctx();
57
51
  const server = new McpServer({ name: 'harness-device', version: PKG.version });
52
+ const io = interaction(server, { transport: opts.transport || 'stdio' });
58
53
  const tool = (name, description, inputSchema, fn) =>
59
- server.registerTool(name, { description, inputSchema }, async (args) => {
54
+ (opts.allow && !opts.allow(name)) ? undefined : server.registerTool(name, { description, inputSchema }, async (args) => {
55
+ const a = args || {};
56
+ const c = ctx();
60
57
  try {
61
- return await fn(ctx(), args || {});
58
+ return await fn(c, a, {
59
+ ask: (message, properties, required) => io.ask(c, name, a, message, properties, required),
60
+ confirm: (message) => io.confirm(c, name, a, message),
61
+ });
62
62
  } catch (e) {
63
63
  if (e instanceof resources.ResourceDenied) return fail(`${e.message}\n${resources.summary(e.sample)}`);
64
- return e instanceof Cancelled ? text(e.message) : fail(e);
64
+ return e instanceof Cancelled || e instanceof NeedsUser ? text(e.message) : fail(e);
65
65
  }
66
66
  });
67
67
 
@@ -76,11 +76,11 @@ export function buildServer(env = process.env) {
76
76
 
77
77
  tool('proc_add', 'Register a long-running process so it keeps running across crashes and reboots, in tmux window proc-<name>. Use this instead of running servers in the foreground. Re-adding a name replaces it.',
78
78
  { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), dir: z.string().optional().describe('absolute working directory (asked if missing)'), command: z.string().optional().describe('one shell line, e.g. "npm run dev -- --port 5173" (asked if missing)'), ...FORCE },
79
- async (c, a) => {
79
+ async (c, a, u) => {
80
80
  await guard(c, a, `starting process ${a.name}`);
81
81
  if (!a.dir || !a.command) {
82
82
  const first = c.projects[0];
83
- const got = await ask(server, `Details for the long-running process "${a.name}"`, {
83
+ const got = await u.ask(`Details for the long-running process "${a.name}"`, {
84
84
  ...(a.dir ? {} : { dir: { type: 'string', title: 'Working directory', description: 'Absolute path, usually the project folder', ...(first ? { default: first.dir } : {}) } }),
85
85
  ...(a.command ? {} : { command: { type: 'string', title: 'Command', description: 'One shell line, e.g. npm run dev -- --port 5173' } }),
86
86
  });
@@ -91,9 +91,9 @@ export function buildServer(env = process.env) {
91
91
  return text(`proc ${a.name} registered; window proc-${a.name}; logs: logs tool with target "proc-${a.name}"`);
92
92
  });
93
93
 
94
- tool('proc_remove', 'Stop and unregister a long-running process.', { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/) },
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.`);
94
+ tool('proc_remove', 'Stop and unregister a long-running process (asks the user first).', { name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,39}$/), ...CONFIRM },
95
+ async (c, a, u) => {
96
+ await u.confirm(`Stop and unregister process "${a.name}"? It will no longer restart or come back after a reboot.`);
97
97
  state.removeProc(c, a.name);
98
98
  return text(`proc ${a.name} removed`);
99
99
  });
@@ -147,8 +147,18 @@ export function buildServer(env = process.env) {
147
147
  }
148
148
 
149
149
  if (has(base, 'docker')) {
150
- tool('docker_summary', 'Containers (all) and Docker disk usage on this device.', {},
151
- async (c) => text(device.dockerSummary(c)));
150
+ tool('docker_summary', 'Containers (all) and Docker disk usage on this device, and running containers with no memory limit (which can take the whole machine).', {},
151
+ async (c) => text({ ...device.dockerSummary(c), noMemoryLimit: device.dockerUnlimited(c).map((x) => `${x.name}${x.managed ? ' (managed by Dokploy/compose/swarm: set its limit there)' : ''}`) }));
152
+ tool('docker_limit', 'Set a memory (and optional CPU) limit on a running container with docker update (asks the user first). memory defaults to RES_CONTAINER_MEM_DEFAULT. Containers Dokploy, compose or swarm manage are refused: their next deploy would drop the limit, so set it in Dokploy (or the compose file) instead.',
153
+ { container: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/), memory: z.string().regex(/^\d+(\.\d+)?[mMgG]$/).optional().describe('e.g. 512m, 1.5g'), cpus: z.number().min(0.1).max(64).optional(), ...CONFIRM },
154
+ async (c, a, u) => {
155
+ const row = device.dockerUnlimited(c, true).find((x) => x.name === a.container || x.id.startsWith(a.container));
156
+ if (!row) throw new Error(`No running container "${a.container}"`);
157
+ if (row.managed) throw new Error(`${row.name} is managed by Dokploy/compose/swarm; docker update would be lost on its next deploy. Set its memory limit in Dokploy (application → Advanced → Resources) or in its compose file.`);
158
+ const memory = a.memory || `${limits.mb(limits.limits(c.cfg).containerMem)}m`;
159
+ await u.confirm(`Limit container ${row.name} to ${memory} of RAM${a.cpus ? ` and ${a.cpus} CPUs` : ''}? If it needs more it is stopped by the kernel (out of memory) instead of slowing the whole machine.`);
160
+ return text(device.dockerLimit(c, row.name, memory, a.cpus));
161
+ });
152
162
  }
153
163
 
154
164
  if (has(base, 'ngrok')) {
@@ -156,12 +166,12 @@ export function buildServer(env = process.env) {
156
166
  async () => text(await device.ngrokStatus()));
157
167
  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
168
  { 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) => {
169
+ async (c, a, u) => {
160
170
  let tunnels = a.tunnels || [];
161
171
  let ports = a.ports || [];
162
172
  if (!tunnels.length && !ports.length) {
163
173
  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?', {
174
+ const got = await u.ask('What should get a public URL?', {
165
175
  tunnel: { type: 'string', title: 'Tunnel', enum: [...names, 'app port'], description: 'An existing tunnel, or "app port" for a local server' },
166
176
  port: { type: 'integer', title: 'App port', minimum: 1, maximum: 65535, description: 'Only for "app port", e.g. 3000' },
167
177
  }, ['tunnel']);
@@ -172,20 +182,35 @@ export function buildServer(env = process.env) {
172
182
  }
173
183
  return text(await device.ngrokUp(c, { tunnels, ports }));
174
184
  });
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?');
185
+ tool('ngrok_down', 'Close every ngrok tunnel on this device (asks the user first).', { ...CONFIRM },
186
+ async (c, a, u) => {
187
+ await u.confirm('Close every public ngrok URL on this device?');
178
188
  c.platform.ngrokDown(c);
179
189
  return text('ngrok tunnels closed');
180
190
  });
181
191
  }
182
192
 
193
+ tool('disk_cleanup', 'Free disk space safely. Without apply it only lists what could go (Docker build cache, dangling images, old stopped containers not managed by Dokploy/compose, npm/pnpm/pip caches, the user journal, Playwright reports, harness logs) with sizes. apply=true removes the chosen items (all when items is empty) after the user confirms. Never removes volumes, databases or anything Dokploy runs.',
194
+ { apply: z.boolean().optional(), items: z.array(z.string().regex(/^[a-z0-9-]+$/)).max(20).optional().describe('ids from the listing; empty = all cleanable'), ...CONFIRM },
195
+ async (c, a, u) => {
196
+ const items = cleanup.plan(c);
197
+ const d = cleanup.describe(items);
198
+ if (!a.apply) return text({ ...d, next: 'To free it, ask the user which items (AskUserQuestion, multiSelect) and call disk_cleanup with apply=true and those items.' });
199
+ const ids = a.items || [];
200
+ const chosen = cleanup.describe(items.filter((i) => !i.listOnly && (!ids.length || ids.includes(i.id))));
201
+ if (!chosen.items.length) return text('Nothing to clean.');
202
+ await u.confirm(`Free about ${chosen.total} by removing: ${chosen.items.map((i) => `${i.id} (${i.size})`).join(', ')}? These are caches and leftovers that rebuild themselves; no data or running app is touched.`);
203
+ const r = cleanup.apply(c, ids, items);
204
+ state.event(c, `disk_cleanup freed ${r.freed}: ${r.done.map((x) => x.id).join(', ')}`);
205
+ return text(r);
206
+ });
207
+
183
208
  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)));
209
+ async (c) => text({ ...(await resources.sample(c)), ...(c.env.HD_CONTAINER === '1' ? {} : { limits: limits.report(c) }) }));
185
210
 
186
211
  tool('upgrade', 'Upgrade harness-device on this device (the user approves this call); check=true only reports. npm installs go to the newest version (or `version`); source-folder installs apply the folder\'s current code. Runs in the background without stopping sessions or unchanged services. restart (default true) then restarts the device gracefully so every session, this one included, loads the new tools and resumes its conversation about a minute later: tell the user before calling.',
187
- { check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional(), restart: z.boolean().optional() },
188
- async (c, a) => {
212
+ { check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional(), restart: z.boolean().optional(), ...CONFIRM },
213
+ async (c, a, u) => {
189
214
  const chk = await upgrader.check(c, { to: a.version });
190
215
  if (a.check) return text(chk);
191
216
  const restart = a.restart !== false;
@@ -193,7 +218,7 @@ export function buildServer(env = process.env) {
193
218
  if (!folder && !chk.available) return text({ ...chk, note: chk.note || `already on ${chk.current}` });
194
219
  if (chk.source === 'none') return text({ ...chk, note: 'not installed on this device yet' });
195
220
  const what = folder ? `Apply the harness-device code in its source folder (${chk.current}) now?` : `Upgrade harness-device ${chk.current} → ${chk.latest} now?`;
196
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `${what} Sessions keep running while it installs${restart ? '; then the device restarts gracefully and every session (this one too) resumes its conversation in about a minute' : ''}.`);
221
+ await u.confirm(`${what} Sessions keep running while it installs${restart ? '; then the device restarts gracefully and every session (this one too) resumes its conversation in about a minute' : ''}.`);
197
222
  const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
198
223
  const args = [path.join(c.paths.bin, 'harness-device'), 'upgrade', ...(folder ? ['--apply'] : ['--to', chk.latest]), ...(restart ? ['--restart'] : []), ...(own ? ['--except', own] : [])];
199
224
  c.platform.spawnDetached(c, 'upgrade', args, path.join(c.paths.logs, 'upgrade.log'));
@@ -201,9 +226,9 @@ export function buildServer(env = process.env) {
201
226
  });
202
227
 
203
228
  tool('device_restart', 'Gracefully restart the whole device (the user approves this call): waits for other sessions to finish their turn, ends sessions and processes cleanly, saves the browser, restarts every service. This session ends too and resumes the same conversation about a minute later; tell the user before calling. Stopping the device is done at the machine (harness-device stop), not from a session.',
204
- { now: z.boolean().optional().describe("don't wait for other sessions to finish their turn") },
205
- async (c, a) => {
206
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, 'Restart the whole device now? Every session (this one too) ends and resumes its conversation in about a minute; public URLs close.');
229
+ { now: z.boolean().optional().describe("don't wait for other sessions to finish their turn"), ...CONFIRM },
230
+ async (c, a, u) => {
231
+ await u.confirm('Restart the whole device now? Every session (this one too) ends and resumes its conversation in about a minute; public URLs close.');
207
232
  // The calling session's own turn is still open: don't wait for it.
208
233
  const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
209
234
  const bin = path.join(c.paths.bin, 'harness-device');
@@ -215,9 +240,9 @@ export function buildServer(env = process.env) {
215
240
  async (c) => text(Object.fromEntries(Object.keys(SETTABLE_KEYS).map((k) => [k, c.cfg[k] ?? '']))));
216
241
  tool('config_set', `Change one device setting (the user approves this call). Never edit files in the device home instead. Keys: ${Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k} (${d})`).join('; ')}. Secrets, capabilities, projects and service ports are changed on the machine, not here.`,
217
242
  { key: z.enum(Object.keys(SETTABLE_KEYS)).optional(), value: z.string().max(200).optional() },
218
- async (c, a) => {
243
+ async (c, a, u) => {
219
244
  if (!a.key || a.value === undefined) {
220
- const got = await ask(server, 'Change a device setting', {
245
+ const got = await u.ask('Change a device setting', {
221
246
  ...(a.key ? {} : { key: { type: 'string', title: 'Setting', enum: Object.keys(SETTABLE_KEYS), description: Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k}: ${d}`).join('; ') } }),
222
247
  value: { type: 'string', title: 'Value', maxLength: 200, ...(a.key ? { description: SETTABLE_KEYS[a.key] } : {}) },
223
248
  });
@@ -54,7 +54,7 @@ function intervalSeconds(s) {
54
54
  return m[2] && m[2].startsWith('m') ? n * 60 : m[2] === 'h' ? n * 3600 : n;
55
55
  }
56
56
 
57
- export const LAUNCHABLE = ['harness-tmux', 'harness-chromium', 'harness-ttyd', 'harness-heal', 'harness-ngrok'];
57
+ export const LAUNCHABLE = ['harness-tmux', 'harness-chromium', 'harness-ttyd', 'harness-heal', 'harness-ngrok', 'harness-serve'];
58
58
  export const launcherName = (u) => `harness-device-${u.replace(/^harness-/, '')}`;
59
59
 
60
60
  /** Named copies of hd-run (see jobs()), replaced atomically like every script. */
@@ -89,6 +89,7 @@ export function jobs(ctx, detect = true) {
89
89
  'harness-ttyd': { args: [run('harness-ttyd'), ttyd, '-i', 'lo0', '-p', c.TTYD_PORT, '-t', 'titleFixed=harness-device', tmux, 'attach', '-r', '-f', 'ignore-size', '-t', `=${c.SESSION}`] },
90
90
  'harness-heal': { args: [run('harness-heal'), b('hd-heal')], keepAlive: false, interval: intervalSeconds(c.HEAL_INTERVAL) },
91
91
  'harness-ngrok': { args: [run('harness-ngrok'), b('hd-ngrok')] },
92
+ 'harness-serve': { args: [run('harness-serve'), b('harness-device'), 'serve'] },
92
93
  };
93
94
  return (u) => {
94
95
  const d = def[u];
@@ -5,6 +5,7 @@ import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
7
  import { PKG_ROOT, run, capture, ok, which, render, writeFile, color } from '../util.js';
8
+ import * as limits from '../limits.js';
8
9
 
9
10
  export const id = 'linux';
10
11
  export const label = 'Linux (systemd user services)';
@@ -32,6 +33,7 @@ export function unitVars(ctx, detect = true) {
32
33
  TTYD_BIN: (detect && which('ttyd', ctx.env)) || '/usr/bin/ttyd',
33
34
  CAPABILITIES: ctx.caps.map((c) => c.id).join(','),
34
35
  WANTS: ctx.units.map(unitName).join(' '),
36
+ ...limits.unitVars(ctx.cfg),
35
37
  };
36
38
  }
37
39
 
@@ -130,7 +130,8 @@ export const interaction = {
130
130
  guidance: () => `## Asking the user
131
131
  The user usually drives this session remotely (phone, claude.ai) and answers by tapping, so ask with interactive prompts, not prose:
132
132
  - **When you need a decision, preference or value, use the \`AskUserQuestion\` tool**, never a question written in your reply. 1-4 questions, 2-4 options each; put the recommended option first and end its label with "(Recommended)"; use multiSelect when choices combine; use the preview field to compare layouts or code. The user can always pick "Other" and type.
133
- - harness-device tools may show their own form (MCP elicitation) for missing details or to confirm something that stops or exposes things. Answer through that; don't ask the same thing again.
133
+ - harness-device tools that stop, expose or change things confirm first. In a Remote Control session (and over \`harness-device serve\`) they do nothing on the first call and reply with what to ask: ask it with \`AskUserQuestion\`, and only on "Go ahead" call the tool again with the \`confirm_token\` it gave (one use, those exact arguments, 10 minutes). Missing details come back the same way. In a local terminal they may show a form instead; answer that and don't ask again.
134
+ - Nothing may wait on this machine's terminal: the user is usually not at it. If something would need a local prompt, ask through \`AskUserQuestion\` instead. For hands-on access the user has the web terminal and display (\`viewers\` tool, opened publicly with \`ngrok_up\`).
134
135
  - Never ask for passwords, API keys or tokens in a question or form. Secrets are entered on the machine (\`harness-device secrets set KEY\`); say that instead.
135
136
  - Never tell the user to run commands on the machine. Ask with options, then do it yourself through the tools.
136
137
  - When a tool returns something the user needs (a URL, a login, a file path), write it plainly in your reply, since prompts disappear once answered.`,
@@ -189,6 +190,8 @@ export function pathRule(tool, abs, home) {
189
190
  */
190
191
  export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-device install:*)',
191
192
  'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)',
193
+ // The serve owner password, and approving/revoking apps, are the owner's.
194
+ 'Bash(harness-device serve:*)',
192
195
  // Stopping ends every session and none could start the device again; restart goes through device_restart.
193
196
  'Bash(harness-device stop:*)', 'Bash(harness-device start:*)', 'Bash(harness-device restart)', 'Bash(harness-device restart --:*)'];
194
197
 
package/src/resources.js CHANGED
@@ -94,7 +94,8 @@ export async function sample(ctx, { quick = false, sampleMs = 400 } = {}) {
94
94
  const memPct = m.total ? Math.round((100 * m.available) / m.total) : 100;
95
95
  const memLevel = memPct <= t.memCritical ? 'critical' : memPct <= t.memHigh ? 'high' : 'ok';
96
96
 
97
- const d = disks([ctx.paths.home, ...(ctx.projects || []).map((p) => p.dir)]);
97
+ // In a container the host's disk is mounted read-only at HD_HOST_ROOT.
98
+ const d = disks(ctx.env && ctx.env.HD_HOST_ROOT ? [ctx.env.HD_HOST_ROOT] : [ctx.paths.home, ...(ctx.projects || []).map((p) => p.dir)]);
98
99
  for (const x of d) {
99
100
  x.level = x.freePct <= t.diskCritical || x.free < 1 * GiB ? 'critical' : x.freePct <= t.diskHigh || x.free < 5 * GiB ? 'high' : 'ok';
100
101
  }
@@ -155,7 +156,7 @@ export async function gate(ctx, { force = false, waitSeconds, what = 'this', qui
155
156
  const LIGHT = [
156
157
  /^(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
158
  /^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
+ /^harness-device (status|logs|events|resources|limits|cleanup|gate|doctor|proc (list|rm)|session list|ngrok (status|down)|config get|tunnel)\b/,
159
160
  /^docker (ps|stop|kill|rm|rmi|logs|stats|system (df|prune)|image (ls|prune)|container (ls|prune)|volume (ls|prune)|builder prune)\b/,
160
161
  /^tmux (ls|list-\w+|kill-window|display-message|capture-pane|has-session)\b/,
161
162
  /^(npm|pnpm|yarn) cache (clean|verify)\b/,
@@ -0,0 +1,129 @@
1
+ // `harness-device serve …` on the machine: run the server, manage the owner
2
+ // password, list/revoke connected apps, and route a domain to it in Dokploy.
3
+
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { readSecrets } from '../context.js';
8
+ import { loadConfig, saveConfig, setSecret, validateConfig } from '../config.js';
9
+ import { capture, log, color, which } from '../util.js';
10
+ import { DeviceOAuth } from './oauth.js';
11
+
12
+ const DOKPLOY_DYNAMIC = '/etc/dokploy/traefik/dynamic';
13
+
14
+ export function ensurePassword(ctx, { rotate = false } = {}) {
15
+ if (ctx.env.SERVE_OWNER_PASSWORD && !rotate) return { password: ctx.env.SERVE_OWNER_PASSWORD, created: false };
16
+ const cur = readSecrets(ctx.paths.secrets).SERVE_OWNER_PASSWORD;
17
+ if (cur && !rotate) return { password: cur, created: false };
18
+ const pw = crypto.randomBytes(18).toString('base64url');
19
+ setSecret(ctx.paths.secrets, 'SERVE_OWNER_PASSWORD', pw);
20
+ return { password: pw, created: true };
21
+ }
22
+
23
+ const oauth = (ctx) => new DeviceOAuth({ file: path.join(ctx.paths.state, 'oauth.json'), password: () => '', device: ctx.cfg.DEVICE });
24
+
25
+ /** The IP Dokploy's Traefik reaches this host on: the gateway of its Docker network. */
26
+ export function traefikGateway(env) {
27
+ if (!which('docker', env)) return '';
28
+ const names = capture('docker', ['ps', '--format', '{{.Names}}', '--filter', 'name=traefik'], { env }).split('\n').filter(Boolean);
29
+ for (const n of names) {
30
+ const gw = capture('docker', ['inspect', n, '--format', '{{range .NetworkSettings.Networks}}{{.Gateway}} {{end}}'], { env }).split(/\s+/).find((x) => /^\d+\.\d+\.\d+\.\d+$/.test(x));
31
+ if (gw) return gw;
32
+ }
33
+ return '';
34
+ }
35
+
36
+ export function traefikConfig(domain, upstream) {
37
+ return `# harness-device serve: https://${domain} → ${upstream} (written by harness-device serve expose)
38
+ http:
39
+ routers:
40
+ harness-device-mcp:
41
+ rule: Host(\`${domain}\`)
42
+ entryPoints: [websecure]
43
+ service: harness-device-mcp
44
+ tls:
45
+ certResolver: letsencrypt
46
+ harness-device-mcp-http:
47
+ rule: Host(\`${domain}\`)
48
+ entryPoints: [web]
49
+ middlewares: [harness-device-https]
50
+ service: harness-device-mcp
51
+ middlewares:
52
+ harness-device-https:
53
+ redirectScheme:
54
+ scheme: https
55
+ permanent: true
56
+ services:
57
+ harness-device-mcp:
58
+ loadBalancer:
59
+ servers:
60
+ - url: "${upstream}"
61
+ `;
62
+ }
63
+
64
+ export async function run(ctx, sub, rest, f) {
65
+ switch (sub) {
66
+ case undefined:
67
+ case 'start': {
68
+ const { created } = ensurePassword(ctx);
69
+ if (created) log.info(`Created the owner password (SERVE_OWNER_PASSWORD in ${ctx.paths.secrets}); see it with: harness-device serve password`);
70
+ const { startServe } = await import('./http.js');
71
+ const s = await startServe(ctx.env, { host: f.host, port: f.port });
72
+ log.ok(`serving ${ctx.cfg.DEVICE}'s tools: MCP ${s.mcpUrl} (OAuth; approve apps with the owner password)`);
73
+ const stop = async () => { await s.close(); process.exit(0); };
74
+ process.on('SIGTERM', stop);
75
+ process.on('SIGINT', stop);
76
+ return new Promise(() => {}); // runs until stopped
77
+ }
78
+
79
+ case 'password': {
80
+ const { password, created } = ensurePassword(ctx, { rotate: !!f.rotate });
81
+ if (created) log.ok(`${f.rotate ? 'New' : 'Created the'} owner password (stored as SERVE_OWNER_PASSWORD in ${ctx.paths.secrets}). Apps already approved keep their tokens; revoke them with harness-device serve revoke.`);
82
+ return console.log(password);
83
+ }
84
+
85
+ case 'clients': {
86
+ const list = oauth(ctx).listClients();
87
+ if (f.json) return console.log(JSON.stringify(list, null, 2));
88
+ if (!list.length) return console.log('(no apps have connected)');
89
+ for (const c of list) console.log(`${c.id} ${c.name || '(unnamed)'} ${c.approved ? color.green(c.scopes.join(' ') || 'approved, no live token') : color.dim('never approved')} ${color.dim(c.redirect)}`);
90
+ return;
91
+ }
92
+
93
+ case 'revoke': {
94
+ if (!rest[0]) throw new Error('usage: harness-device serve revoke <client id> (ids: harness-device serve clients)');
95
+ oauth(ctx).revokeClient(rest[0]);
96
+ return log.ok(`revoked ${rest[0]} and all its tokens`);
97
+ }
98
+
99
+ case 'expose': {
100
+ const domain = f.domain;
101
+ if (!domain || !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(domain)) throw new Error('usage: harness-device serve expose --domain mcp.example.com');
102
+ const gw = f.host || traefikGateway(ctx.env) || '172.17.0.1';
103
+ const port = ctx.cfg.SERVE_PORT || '7700';
104
+ const { cfg } = loadConfig(ctx.env);
105
+ const next = { ...cfg, SERVE_HOST: gw, SERVE_PUBLIC_URL: `https://${domain}` };
106
+ const errs = validateConfig(next, ctx.env);
107
+ if (errs.length) throw new Error(errs.join(' '));
108
+ saveConfig(next, ctx.env);
109
+ const yml = traefikConfig(domain, `http://${gw}:${port}`);
110
+ const file = path.join(DOKPLOY_DYNAMIC, 'harness-device-mcp.yml');
111
+ let wrote = false;
112
+ try { fs.writeFileSync(file, yml); wrote = true; } catch { /* not writable without root */ }
113
+ log.ok(`SERVE_HOST=${gw} (Traefik's Docker gateway: reachable by Dokploy's Traefik, not from the internet) and SERVE_PUBLIC_URL=https://${domain} saved.`);
114
+ if (wrote) log.ok(`Traefik route written: ${file}`);
115
+ else {
116
+ console.log(`\nSave this as ${file} on the Dokploy server (needs root, e.g. sudo tee ${file}):\n`);
117
+ console.log(yml);
118
+ }
119
+ console.log(`Then:
120
+ 1. DNS: an A record ${domain} → this server's public IP.
121
+ 2. Add "serve" to CAPABILITIES (harness-device init --capabilities …) or keep it, and run: harness-device install
122
+ 3. In the MCP client, add the server ${color.bold(`https://${domain}/mcp`)}; approve it with: harness-device serve password`);
123
+ return;
124
+ }
125
+
126
+ default:
127
+ throw new Error(`Unknown: serve ${sub}. Use serve, serve password, serve clients, serve revoke <id>, serve expose --domain D`);
128
+ }
129
+ }
@@ -0,0 +1,120 @@
1
+ // `harness-device serve`: the device's MCP tools over Streamable HTTP, behind
2
+ // OAuth, for any MCP client (claude.ai connectors, other agents, scripts),
3
+ // not only the Remote Control sessions on this machine.
4
+ //
5
+ // /mcp MCP (Bearer token; tools filtered by its scopes)
6
+ // /authorize /token /register /revoke OAuth 2.1 (MCP SDK router + DeviceOAuth)
7
+ // /.well-known/oauth-* discovery metadata
8
+ // /healthz liveness, no auth
9
+ //
10
+ // It binds SERVE_HOST:SERVE_PORT (127.0.0.1:7700). The public URL
11
+ // (SERVE_PUBLIC_URL, https) is where Traefik/Dokploy or ngrok routes to it.
12
+
13
+ import crypto from 'node:crypto';
14
+ import path from 'node:path';
15
+ import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
16
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
17
+ import { mcpAuthRouter, getOAuthProtectedResourceMetadataUrl } from '@modelcontextprotocol/sdk/server/auth/router.js';
18
+ import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js';
19
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
20
+ import { loadContext, readSecrets } from '../context.js';
21
+ import { buildServer } from '../mcp/server.js';
22
+ import { PKG } from '../util.js';
23
+ import { DeviceOAuth } from './oauth.js';
24
+ import { SCOPES, allowFor } from './scopes.js';
25
+ import { isContainer, CONTAINER_TOOLS } from '../container.js';
26
+
27
+ const IDLE_MS = 60 * 60 * 1000;
28
+
29
+ /** Where clients reach the server, from config (or the bind address). */
30
+ export function publicUrl(cfg, host, port) {
31
+ if (cfg.SERVE_PUBLIC_URL) return new URL(cfg.SERVE_PUBLIC_URL.replace(/\/+$/, '') + '/');
32
+ const h = ['0.0.0.0', '::'].includes(host) ? '127.0.0.1' : host;
33
+ return new URL(`http://${h.includes(':') ? `[${h}]` : h}:${port}/`);
34
+ }
35
+
36
+ /**
37
+ * Start the server. Returns { url, close }. opts.host / opts.port override
38
+ * config; opts.password overrides the secret (tests).
39
+ */
40
+ export async function startServe(env = process.env, opts = {}) {
41
+ const ctx = loadContext(env);
42
+ const host = opts.host || ctx.cfg.SERVE_HOST || '127.0.0.1';
43
+ const port = Number(opts.port ?? ctx.cfg.SERVE_PORT ?? 7700);
44
+ const base = opts.publicUrl ? new URL(opts.publicUrl) : publicUrl(ctx.cfg, host, port);
45
+ const mcpUrl = new URL('mcp', base);
46
+ // A container gets it from its environment (a Dokploy secret); a host from secrets.env.
47
+ const password = opts.password ? () => opts.password : () => env.SERVE_OWNER_PASSWORD || readSecrets(ctx.paths.secrets).SERVE_OWNER_PASSWORD;
48
+ const inContainer = isContainer(env);
49
+ if (!password()) throw new Error('No owner password yet: run harness-device serve password (it creates one) and start again.');
50
+
51
+ const provider = new DeviceOAuth({ file: path.join(ctx.paths.state, 'oauth.json'), password, device: ctx.cfg.DEVICE });
52
+ const app = createMcpExpressApp({ host, allowedHosts: [...new Set([base.hostname, 'localhost', '127.0.0.1', host])] });
53
+ // Behind Traefik (a Docker network) or the ngrok agent (loopback): rate limits see the real client.
54
+ app.set('trust proxy', 'loopback, uniquelocal');
55
+ app.disable('x-powered-by');
56
+
57
+ app.get('/healthz', (_req, res) => res.json({ ok: true, device: ctx.cfg.DEVICE, version: PKG.version }));
58
+ app.use(mcpAuthRouter({
59
+ provider,
60
+ issuerUrl: base,
61
+ resourceServerUrl: mcpUrl,
62
+ scopesSupported: Object.keys(SCOPES),
63
+ resourceName: `harness-device ${ctx.cfg.DEVICE}`,
64
+ }));
65
+
66
+ const sessions = new Map(); // mcp-session-id → { transport, clientId, last }
67
+ const auth = requireBearerAuth({ verifier: provider, resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpUrl) });
68
+ const rpcError = (res, status, message) => res.status(status).json({ jsonrpc: '2.0', error: { code: -32000, message }, id: null });
69
+
70
+ app.all('/mcp', auth, async (req, res) => {
71
+ try {
72
+ const sid = req.headers['mcp-session-id'];
73
+ if (sid) {
74
+ const s = sessions.get(sid);
75
+ if (!s) return rpcError(res, 404, 'Unknown or expired session; initialize again');
76
+ // A session belongs to the client (and scopes) that opened it.
77
+ if (s.clientId !== req.auth.clientId) return rpcError(res, 403, 'This session belongs to another client');
78
+ s.last = Date.now();
79
+ return await s.transport.handleRequest(req, res, req.body);
80
+ }
81
+ if (req.method !== 'POST' || !isInitializeRequest(req.body)) return rpcError(res, 400, 'Send initialize first (no mcp-session-id)');
82
+ const scopes = req.auth.scopes;
83
+ const transport = new StreamableHTTPServerTransport({
84
+ sessionIdGenerator: () => crypto.randomUUID(),
85
+ onsessioninitialized: (id) => sessions.set(id, { transport, clientId: req.auth.clientId, last: Date.now() }),
86
+ });
87
+ transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); };
88
+ const byScope = allowFor(scopes);
89
+ const allow = inContainer ? (name) => CONTAINER_TOOLS.includes(name) && byScope(name) : byScope;
90
+ const server = buildServer(env, { transport: 'http', allow });
91
+ await server.connect(transport);
92
+ await transport.handleRequest(req, res, req.body);
93
+ } catch (e) {
94
+ console.error(`serve: ${e && e.stack ? e.stack : e}`);
95
+ if (!res.headersSent) rpcError(res, 500, 'Internal error');
96
+ }
97
+ });
98
+
99
+ const sweep = setInterval(() => {
100
+ for (const [id, s] of sessions) if (Date.now() - s.last > IDLE_MS) { sessions.delete(id); s.transport.close().catch(() => {}); }
101
+ }, 60000);
102
+ sweep.unref();
103
+
104
+ const srv = await new Promise((resolve, reject) => {
105
+ const s = app.listen(port, host, () => resolve(s));
106
+ s.on('error', reject);
107
+ });
108
+ const actual = srv.address().port;
109
+ return {
110
+ url: opts.publicUrl || ctx.cfg.SERVE_PUBLIC_URL ? base.href : `http://${base.hostname}:${actual}/`,
111
+ port: actual,
112
+ mcpUrl: opts.publicUrl || ctx.cfg.SERVE_PUBLIC_URL ? mcpUrl.href : `http://${base.hostname}:${actual}/mcp`,
113
+ provider,
114
+ close: async () => {
115
+ clearInterval(sweep);
116
+ for (const s of sessions.values()) await s.transport.close().catch(() => {});
117
+ await new Promise((r) => srv.close(r));
118
+ },
119
+ };
120
+ }