@dreamtree-org/harness-device 0.1.1 → 0.1.3

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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.3
4
+
5
+ Remote first: everything a session does on the device, you approve from the session; nothing needs you at the machine, and the session never edits the device's own files.
6
+
7
+ - **New MCP tools** (each asks your approval in the session): `ngrok_up` (groups, single tunnels or app ports; returns the URL and the login), `ngrok_down`, `config_set`. Read-only `config_get` is pre-approved.
8
+ - **`harness-device config get|set`** for the settings a session may change: `NGROK_APP_PORTS`, `NGROK_APPS_PUBLIC`, `NGROK_DOMAIN`, the Dokploy tool filters, `TRANSCRIPT_DAYS`. Secrets, capabilities, projects and service ports stay with `init`/`install`/`secrets` on the machine.
9
+ - **`ngrok up --port 8099`** adds an app port and opens just that tunnel.
10
+ - **Denied in sessions:** editing anything under `~/.harness-device`, and `harness-device init`/`install`/`uninstall`/`secrets`.
11
+ - **Interactive questions:** the skill tells the agent to ask with the provider's interactive prompt (Claude: `AskUserQuestion`, tappable options) instead of questions in prose, never to ask for secrets, and to restate URLs and logins in its reply. Each provider declares this in `interaction` (`askTool`, `supportsElicitation`, `guidance`).
12
+ - **Forms from the device's tools (MCP elicitation):** `ngrok_up`, `config_set` and `proc_add` ask for what's missing in a form (`ngrok_up` lists this device's tunnels); `ngrok_down` and `proc_remove` ask to confirm. Declining changes nothing. Clients without forms get an error naming the missing fields.
13
+ - **Skill:** use the device's tools instead of editing its files, keep test files in the project folder, and never ask the user to run commands on the machine.
14
+
15
+ ## 0.1.2
16
+
17
+ - **Dokploy:** secret fields in API responses are redacted before they reach the agent; optional `DOKPLOY_TOOL_PRESET` / `DOKPLOY_ENABLED_TAGS` / `DOKPLOY_DISABLED_TAGS` in config.env limit the tools loaded.
18
+ - **ngrok:** Intel Macs get ngrok's official release in `~/.local/bin`; `ngrok up` waits for every tunnel and lists it; one tunnel can be opened by name (`ngrok up ttyd`); a warning when tunnels share the single URL of a free plan.
19
+ - **Install summary** lists only the MCP servers it registered, and names the ones of yours it kept.
20
+ - `.env` and `.playwright-mcp/` are git-ignored.
21
+
3
22
  ## 0.1.1
4
23
 
5
24
  Fixes from the first installs on a real Mac (Intel) and checks on Ubuntu 26.04.
package/README.md CHANGED
@@ -123,6 +123,8 @@ harness-device install
123
123
  harness-device doctor # "Dokploy API accepts the key"
124
124
  ```
125
125
 
126
+ Secrets in Dokploy's API responses (env vars, passwords, tokens) are redacted before they reach the agent (`DOKPLOY_REDACT_ENV=true`). To load fewer Dokploy tools, add any of these to `config.env` and run `install` again: `DOKPLOY_TOOL_PRESET`, `DOKPLOY_ENABLED_TAGS=project,application,postgres`, `DOKPLOY_DISABLED_TAGS`. If you already have your own `dokploy` MCP server, install leaves it as it is and the device's is not registered.
127
+
126
128
  ### Updating
127
129
 
128
130
  Run `install` again with the new version: `npx @dreamtree-org/harness-device@latest install`. It is idempotent. It updates scripts, services, MCP registrations and the skill, and never restarts the tmux session, so live conversations keep running. Add or drop capabilities the same way: `init --with …` / `--without …`, then `install`.
@@ -144,7 +146,8 @@ Run `install` again with the new version: `npx @dreamtree-org/harness-device@lat
144
146
  | `restart <service>` | Restart one harness service |
145
147
  | `tunnel` | The SSH command for the viewers |
146
148
  | `secrets set KEY`, `secrets list`, `secrets rm KEY` | API keys for MCP servers, stored mode 600. Only the MCP servers get them, not the agent's environment |
147
- | `ngrok token`, `ngrok up viewers\|apps\|all`, `ngrok down`, `ngrok status` | Public URLs, off until you turn them on |
149
+ | `ngrok token`, `ngrok up [viewers\|apps\|all\|<tunnel>] [--port 8099]`, `ngrok down`, `ngrok status` | Public URLs, off until you turn them on |
150
+ | `config get [KEY]`, `config set KEY=VALUE` | The settings a remote session may change (app ports, Dokploy tool filters, transcript days) |
148
151
  | `mcp` | The harness-device MCP server (stdio) |
149
152
  | `fleet add <name> <user@host>`, `fleet status`, `fleet run <name> <args>` | Many devices from one machine, over ssh |
150
153
  | `uninstall [--purge]` | Remove services and agent wiring (`--purge` also deletes state and config) |
@@ -164,7 +167,7 @@ Pick them with `init --with`/`--without`, or edit `CAPABILITIES=` in `config.env
164
167
  | `docker` | Docker Engine (`get.docker.com`) | Docker Desktop, else colima | `docker`, `docker compose` |
165
168
  | `dokploy` | API only | API only | Dokploy MCP against your deployment (`DOKPLOY_URL` + `secrets set DOKPLOY_API_KEY`); nothing is installed |
166
169
  | `graphify` | | | `@dreamtree-org/graphify` CLI; `graphify .` wires a project's graph MCP and hooks |
167
- | `ngrok` | apt repo | Homebrew (Intel: ngrok.com download) | Tunnels you open; the agent may only read them |
170
+ | `ngrok` | apt repo | Homebrew (Intel: ngrok's official release, into `~/.local/bin`) | Tunnels you open; the agent may only read them |
168
171
  | `ollama` | ollama.com script | Homebrew (Intel: Ollama app) | Local models on 127.0.0.1:11434 (`OLLAMA_MODELS` pulled on install) |
169
172
 
170
173
  Extra MCP servers for the agent: add `MCP_<name>=command args` lines to `config.env`. They run through `hd-with-secrets`, so API keys stay in `secrets.env`.
@@ -174,9 +177,13 @@ Extra MCP servers for the agent: add `MCP_<name>=command args` lines to `config.
174
177
  Remote sessions run commands without anyone at the keyboard, so `install` merges a curated list into `~/.claude/settings.json`. It only ever adds or removes its own entries.
175
178
 
176
179
  - **Pre-approved:** git, npm/npx/node, tmux, curl, docker, sqlite3, graphify, `hd-pw-live`, read-only system commands, the read-only `harness-device` subcommands (`status`, `logs`, `proc list`, `session list`/`new`…), the Playwright and graphify MCP tools, and the harness-device MCP tools that only read (status, sessions, logs, viewers, screenshot…) or restart the browser.
177
- - **Denied:** `sudo`, `su`, shutdown/reboot, `mkfs`, `dd`, `rm -rf` of `/` or home, `tmux kill-server`/`kill-session`, and reading `secrets.env`, the ngrok config and `~/.ssh`.
180
+ - **Denied:** `sudo`, `su`, shutdown/reboot, `mkfs`, `dd`, `rm -rf` of `/` or home, `tmux kill-server`/`kill-session`, reading `secrets.env`, the ngrok config and `~/.ssh`, **editing anything in `~/.harness-device`**, and `harness-device init`/`install`/`uninstall`/`secrets`.
178
181
  - **Never from inside a session:** restarting tmux (it holds every live session); the MCP tool refuses it, and the CLI asks for `--force`.
179
- - **Everything else asks you**, including Dokploy deploys, registering or removing processes (`proc add`/`rm`), and anything that changes `harness-device` itself (`uninstall`, `ngrok up`, `session reset`).
182
+ - **Everything else asks you**, including Dokploy deploys, registering or removing processes (`proc_add`/`proc_remove`), opening public URLs (`ngrok_up`/`ngrok_down`), changing settings (`config_set`) and `session reset`.
183
+
184
+ **Remote first.** You approve those prompts in the session itself, on your phone or claude.ai, so nothing a session does needs you at the machine. A session changes the device only through these tools, never by editing its files, and never asks you to type commands on the machine. Only three things need the machine (locally or over SSH): entering secrets, `init`/`install` (capabilities, projects, upgrades) and the first `claude` login.
185
+
186
+ **Interactive questions.** When the agent needs a decision it asks with the provider's interactive prompt (in Claude, `AskUserQuestion`: tappable options plus "Other"), not a question in prose. The device's own tools show forms for missing details and confirmations (MCP elicitation: pick a tunnel, enter a port, confirm closing URLs). Neither ever asks for a secret.
180
187
 
181
188
  This is a guard against accidents, not a sandbox. Pre-approving `node`, `npx` and `npm` already lets the agent run any code as your user, so give a device only the projects and credentials you would give the agent anyway.
182
189
 
@@ -201,7 +208,7 @@ harness-device fleet status # every device: sessions, failing slots, serv
201
208
 
202
209
  ## Security
203
210
 
204
- - Nothing listens publicly. CDP, noVNC, ttyd and Playwright UI bind to 127.0.0.1, and Remote Control is outbound HTTPS only. ngrok tunnels open only when you run `ngrok up`, and viewer and app tunnels require basic auth.
211
+ - Nothing listens publicly. CDP, noVNC, ttyd and Playwright UI bind to 127.0.0.1, and Remote Control is outbound HTTPS only. ngrok tunnels open only when you run `ngrok up` or approve `ngrok_up` in a session, and viewer and app tunnels require basic auth (the approved tool returns the login so you can sign in from your phone).
205
212
  - `ANTHROPIC_API_KEY` and similar are stripped from sessions (an API key would bypass the claude.ai login that Remote Control needs), and `secrets set` refuses to store them.
206
213
  - `docker` access is root-equivalent on Linux. Leave the `docker` capability off on a device you share.
207
214
 
@@ -221,7 +228,7 @@ Logs: `harness-device logs <project|proc-name|service> [-f]`.
221
228
  ## What it deliberately does NOT do
222
229
 
223
230
  - **Install Dokploy, or any server software beyond the tools above.** Dokploy is used through the API of your existing deployment.
224
- - **Open public URLs on its own.** ngrok stays off until you run `ngrok up`, and the agent can only read tunnel status.
231
+ - **Open public URLs on its own.** ngrok stays off until you open a tunnel or approve the agent's `ngrok_up` request.
225
232
  - **Replace a conversation silently.** A failing slot is flagged; only `session reset` starts a new one.
226
233
  - **Sandbox the agent.** It runs as your user, with the approvals above.
227
234
  - **Support Windows, or Linux without systemd and apt** (yet).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Turn a Linux server into a reboot-proof Claude Code harness: Remote Control per project in tmux, a persistent Chromium + Playwright MCP on a virtual display, live viewers (noVNC, ttyd, Playwright UI), self-healing systemd services, plus Docker, Dokploy, ngrok and AI-provider tooling.",
5
5
  "author": {
6
6
  "name": "Partha Preetham Krishna",
@@ -94,8 +94,20 @@ fi
94
94
 
95
95
  if want ngrok; then
96
96
  if ! has ngrok; then
97
- has brew || die "install ngrok from https://ngrok.com/download (put it on your PATH), then re-run install"
98
- brew install ngrok
97
+ if has brew; then
98
+ brew install ngrok
99
+ else
100
+ # Not on conda-forge: ngrok's own release (its official download host), into ~/.local/bin.
101
+ arch=$(uname -m); [ "$arch" = x86_64 ] && arch=amd64
102
+ log "installing ngrok (official release for darwin-$arch) into ~/.local/bin"
103
+ tmp=$(mktemp -d)
104
+ curl -fsSL -o "$tmp/ngrok.zip" "https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-darwin-$arch.zip"
105
+ mkdir -p "$HOME/.local/bin"
106
+ unzip -o -q "$tmp/ngrok.zip" ngrok -d "$HOME/.local/bin"
107
+ chmod 755 "$HOME/.local/bin/ngrok"
108
+ rm -r "$tmp"
109
+ "$HOME/.local/bin/ngrok" version >/dev/null || die "ngrok did not install"
110
+ fi
99
111
  fi
100
112
  fi
101
113
 
@@ -15,6 +15,8 @@ import { listSessions, listProcs } from './state.js';
15
15
 
16
16
  export const PLAYWRIGHT_MCP = '@playwright/mcp@0.0.86';
17
17
  export const DOKPLOY_MCP = '@dokploy/mcp@0.30.7';
18
+ /** Optional @dokploy/mcp tool filters, passed through from config.env when set. */
19
+ export const DOKPLOY_OPTIONS = ['DOKPLOY_TOOL_PRESET', 'DOKPLOY_ENABLED_TAGS', 'DOKPLOY_DISABLED_TAGS'];
18
20
 
19
21
  const isMac = (plat) => plat && plat.id === 'darwin';
20
22
 
@@ -73,7 +75,15 @@ ${cfg.SERVE_MODE === 'server'
73
75
  - A one-off process that only needs to outlive this turn can go in a plain window: \`tmux new-window -d -t ${cfg.SESSION}: -n tmp-<name> -c <dir> '<command>'\` (gone after a reboot).
74
76
  - Docker containers you start: use \`--restart unless-stopped\` (compose: \`restart: unless-stopped\`) so they come back after a reboot.
75
77
  - \`harness-device status\` shows sessions, processes and services; \`harness-device events\` shows what was restored after the last restart.
76
- - \`sudo\` is denied. If something needs root, tell the user the exact command.`,
78
+ - \`sudo\` is denied. If something needs root, tell the user the exact command.
79
+
80
+ ### Changing the device: only through its tools
81
+ The user is usually remote (phone, claude.ai) and can't type on this machine. Everything you change on the device goes through a harness-device tool, which asks the user's approval right here in the session:
82
+ - Settings: \`config_get\` / \`config_set\` (MCP) or \`harness-device config set KEY=VALUE\`. **Never edit files under \`~/.harness-device\`** (config.env, projects.tsv, ngrok files, state, logs) or the service files (systemd units, LaunchAgents), and never copy or back them up by hand.
83
+ - Long-running processes: \`proc_add\` / \`proc_remove\`. Public URLs: \`ngrok_up\` / \`ngrok_down\`.
84
+ - Put your own files (test pages, scripts, data) in the project folder, never in the device home.
85
+ - **Don't ask the user to run commands on the machine** (no \`! ...\` instructions). If no tool covers what you need, say what is missing.
86
+ - Only three things need the machine itself (local or SSH): entering secrets (\`harness-device secrets set\`), \`harness-device init/install\` (capabilities, projects, upgrades) and the first \`claude\` login. Those commands are denied to you.`,
77
87
  },
78
88
 
79
89
  system: {
@@ -105,7 +115,7 @@ ${cfg.SERVE_MODE === 'server'
105
115
  This is a Mac: browsers and headed tests open on its real screen, which the user watches with macOS Screen Sharing (through \`harness-device tunnel\`). This tmux session is viewable read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`.
106
116
  - Screenshot of the screen: the \`screenshot\` MCP tool, or \`screencapture -x /tmp/screen.png\`.`
107
117
  : `## Display and live viewers
108
- A virtual display \`:${cfg.DISPLAY_NUM}\` is always on (\`DISPLAY\` is already set). The user watches it at noVNC \`http://127.0.0.1:${cfg.NOVNC_PORT}/vnc.html\` and this tmux session read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`, over an SSH tunnel (\`harness-device tunnel\`) or ngrok (\`harness-device ngrok up viewers\`).
118
+ A virtual display \`:${cfg.DISPLAY_NUM}\` is always on (\`DISPLAY\` is already set). The user watches it at noVNC \`http://127.0.0.1:${cfg.NOVNC_PORT}/vnc.html\` and this tmux session read-only at \`http://127.0.0.1:${cfg.TTYD_PORT}\`, over an SSH tunnel (\`harness-device tunnel\`) or a public URL from the \`ngrok_up\` tool.
109
119
  - Anything headed you start (browsers, Electron, Playwright \`--headed\`) appears there, so the user can see progress.
110
120
  - Screenshot of the whole display: the \`screenshot\` MCP tool, or \`import -display :${cfg.DISPLAY_NUM} -window root /tmp/screen.png\`.`,
111
121
  },
@@ -159,7 +169,10 @@ You can use \`docker\` and \`docker compose\` directly${isMac(plat) ? ' (the eng
159
169
 
160
170
  dokploy: {
161
171
  label: 'Dokploy (your existing deployment, through its API and the Dokploy MCP)',
162
- mcp: (cfg, p) => [{ name: 'dokploy', command: path.join(p.bin, 'hd-with-secrets'), args: ['env', `DOKPLOY_URL=${cfg.DOKPLOY_URL}`, 'npx', '-y', DOKPLOY_MCP] }],
172
+ // Secrets in API responses (env vars, passwords, tokens) are redacted before
173
+ // they reach the agent; optional tool filters come from config.env.
174
+ mcp: (cfg, p) => [{ name: 'dokploy', command: path.join(p.bin, 'hd-with-secrets'), args: ['env', `DOKPLOY_URL=${cfg.DOKPLOY_URL}`, 'DOKPLOY_REDACT_ENV=true',
175
+ ...DOKPLOY_OPTIONS.filter((k) => cfg[k]).map((k) => `${k}=${cfg[k]}`), 'npx', '-y', DOKPLOY_MCP] }],
163
176
  secrets: ['DOKPLOY_API_KEY'],
164
177
  checks: async (ctx) => {
165
178
  const url = ctx.cfg.DOKPLOY_URL;
@@ -196,7 +209,7 @@ Deployments go through the user's Dokploy at ${cfg.DOKPLOY_URL || '(DOKPLOY_URL
196
209
  { name: 'ngrok authtoken', ok: fs.existsSync(ctx.paths.ngrokToken), warn: true, fix: 'harness-device ngrok token' },
197
210
  ],
198
211
  docs: () => `## ngrok
199
- Public URLs are off by default. Only the user turns them on (\`harness-device ngrok up viewers|apps\`); you may read them with \`harness-device ngrok status\` and share them, but don't open new tunnels yourself.`,
212
+ Public URLs are off by default. To open one, call \`ngrok_up\`: the user approves it here. Examples: \`{"ports":[3000]}\` exposes a dev server (registered with \`proc_add\` from the project folder), \`{"tunnels":["ttyd"]}\` the read-only terminal view. The result has the URL and, for tunnels behind a login, the user name and password: give both to the user. A free ngrok plan has one URL, so open one tunnel at a time. Check with \`ngrok_status\`; close everything with \`ngrok_down\` when the user is done.`,
200
213
  },
201
214
 
202
215
  ollama: {
package/src/cli.js CHANGED
@@ -3,7 +3,7 @@ import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import readline from 'node:readline';
5
5
  import { spawnSync } from 'node:child_process';
6
- import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths } from './config.js';
6
+ import { loadConfig, saveConfig, parseProjectSpec, validateConfig, renderProjectsTsv, paths as getPaths, SETTABLE_KEYS, setConfigValue } from './config.js';
7
7
  import { ORDER, CAPABILITIES } from './capabilities.js';
8
8
  import { loadContext } from './context.js';
9
9
  import { install, uninstall } from './install.js';
@@ -40,7 +40,8 @@ ${color.bold('Device')}
40
40
  status [--json] sessions, processes, services, viewers
41
41
  tunnel ssh command to watch the display, tmux and Playwright UI
42
42
  secrets set <KEY> | list | rm <KEY> API keys for MCP servers (kept out of agent sessions)
43
- ngrok token | up <viewers|apps|all>... | down | status
43
+ config get [KEY] | set KEY=VALUE settings a remote session may change (ngrok, Dokploy filters, transcript days)
44
+ ngrok token | up [viewers|apps|all|<tunnel>]... [--port 8099] | down | status
44
45
  restart <service> restart one harness service (chromium, ttyd, ...)
45
46
  mcp run the harness-device MCP server (stdio)
46
47
 
@@ -53,7 +54,7 @@ Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).j
53
54
  `;
54
55
 
55
56
  const BOOL_FLAGS = ['dryRun', 'skipSystem', 'json', 'purge', 'force', 'follow', 'help', 'version'];
56
- const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl'];
57
+ const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port'];
57
58
 
58
59
  // Commands whose tail is someone else's command line, kept verbatim:
59
60
  // `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
@@ -299,6 +300,27 @@ export async function main(argv) {
299
300
  return log.info(`Then open:\n display ${v.display}\n tmux (r/o) ${v.tmux}\n Playwright ${v.playwrightUi} (while hd-pw-live ui runs)`);
300
301
  }
301
302
 
303
+ case 'config': {
304
+ if (sub === 'set') {
305
+ const kv = rest.join(' ');
306
+ const eq = kv.indexOf('=');
307
+ if (eq < 1) throw new Error('Usage: harness-device config set KEY=VALUE');
308
+ const r = setConfigValue(kv.slice(0, eq).trim(), kv.slice(eq + 1), env);
309
+ log.ok(`${r.key}=${r.value}`);
310
+ if (r.needsInstall) log.info('Applies at the next: harness-device install');
311
+ return;
312
+ }
313
+ if (sub === 'get' || !sub) {
314
+ const { cfg } = loadConfig(env);
315
+ for (const k of rest.length ? rest : Object.keys(SETTABLE_KEYS)) {
316
+ if (!Object.prototype.hasOwnProperty.call(SETTABLE_KEYS, k)) throw new Error(`${k} is not a settable key (${Object.keys(SETTABLE_KEYS).join(', ')})`);
317
+ console.log(`${k}=${cfg[k] ?? ''}`);
318
+ }
319
+ return;
320
+ }
321
+ throw new Error('Usage: harness-device config get [KEY] | set KEY=VALUE');
322
+ }
323
+
302
324
  case 'secrets': {
303
325
  const p = getPaths(env);
304
326
  if (sub === 'set') {
@@ -325,19 +347,13 @@ export async function main(argv) {
325
347
  return log.ok('ngrok authtoken saved. Open tunnels with: harness-device ngrok up viewers');
326
348
  }
327
349
  if (sub === 'up') {
328
- if (!ctx.caps.some((c) => c.id === 'ngrok')) throw new Error('Turn on the ngrok capability first: harness-device init --with ngrok && harness-device install');
329
- if (!fs.existsSync(p.ngrokToken)) throw new Error('No authtoken yet: harness-device ngrok token');
330
- // A password generated at load time must be saved, or the next run makes another.
331
- if (!/^NGROK_VIEWER_PASS=/m.test(fs.existsSync(p.config) ? fs.readFileSync(p.config, 'utf8') : '')) saveConfig(ctx.cfg, env);
332
- const names = ngrok.selectTunnels(ctx.cfg, rest.length ? rest : ['viewers'], ctx.platform.id);
333
- writeFile(p.ngrokYml, ngrok.renderNgrokYml(ctx.cfg, fs.readFileSync(p.ngrokToken, 'utf8').trim(), ctx.platform.id), { mode: 0o600 });
334
- writeFile(p.ngrokEnv, ngrok.renderNgrokEnv(names), { mode: 0o600 });
335
- ctx.platform.ngrokUp(ctx);
336
- await new Promise((r) => setTimeout(r, 4000));
337
- const s = await device.ngrokStatus();
338
- for (const t of s.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
339
- if (names.some((n) => ['novnc', 'ttyd', 'pwui'].includes(n))) log.info(color.dim(` viewer login: ${ctx.cfg.NGROK_VIEWER_USER} / (NGROK_VIEWER_PASS in ${p.config})`));
340
- return log.ok(s.running ? `ngrok up (survives reboots until: harness-device ngrok down)` : 'ngrok did not start yet; check: harness-device logs ngrok');
350
+ const ports = f.port ? String(f.port).split(',') : [];
351
+ const r = await device.ngrokUp(ctx, { tunnels: rest, ports });
352
+ for (const t of r.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
353
+ if (r.shared.length) log.warn(`Your ngrok plan gives one URL, so ${r.shared.join(', ')} share it and each request goes to either at random. Open one at a time (e.g. harness-device ngrok up ttyd), or reserve more domains.`);
354
+ if (r.running && r.missing.length) log.warn(`not up yet: ${r.missing.join(', ')}; check: harness-device ngrok status, harness-device logs ngrok`);
355
+ if (r.login) log.info(color.dim(` login for ${r.login.for.join(', ')}: ${r.login.user} / (NGROK_VIEWER_PASS in ${p.config})`));
356
+ return log.ok(r.running ? `ngrok up (survives reboots until: harness-device ngrok down)` : 'ngrok did not start yet; check: harness-device logs ngrok');
341
357
  }
342
358
  if (sub === 'down') {
343
359
  ctx.platform.ngrokDown(ctx);
@@ -345,7 +361,10 @@ export async function main(argv) {
345
361
  }
346
362
  const s = await device.ngrokStatus();
347
363
  if (!s.running) return console.log('ngrok is not running (harness-device ngrok up <group>)');
364
+ if (!s.tunnels.length) console.log('ngrok is running but no tunnel is up yet (harness-device logs ngrok)');
348
365
  for (const t of s.tunnels) console.log(`${t.name}\t${t.url}\t${t.addr}`);
366
+ const shared = ngrok.sharedUrls(s.tunnels);
367
+ if (shared.length) log.warn(`${shared.join(', ')} share one URL; requests go to either at random`);
349
368
  return;
350
369
  }
351
370
 
package/src/config.js CHANGED
@@ -170,6 +170,9 @@ export function validateConfig(cfg, env = process.env) {
170
170
  if (!['conversation', 'server'].includes(cfg.SERVE_MODE)) errs.push('SERVE_MODE must be conversation or server.');
171
171
  if (!/^\d+$/.test(String(cfg.TRANSCRIPT_DAYS)) || Number(cfg.TRANSCRIPT_DAYS) < 30) errs.push('TRANSCRIPT_DAYS must be a number of days, at least 30.');
172
172
  if (cfg.DOKPLOY_URL && !/^https?:\/\/[^\s'"]+$/.test(cfg.DOKPLOY_URL)) errs.push('DOKPLOY_URL must be an http(s) URL.');
173
+ for (const k of ['DOKPLOY_TOOL_PRESET', 'DOKPLOY_ENABLED_TAGS', 'DOKPLOY_DISABLED_TAGS']) {
174
+ if (cfg[k] && !/^[A-Za-z0-9_,-]+$/.test(cfg[k])) errs.push(`${k} must be a comma-separated list of names (e.g. project,application,postgres).`);
175
+ }
173
176
  for (const k of ['DISPLAY_NUM', 'CDP_PORT', 'VNC_PORT', 'NOVNC_PORT', 'TTYD_PORT', 'PW_UI_PORT']) {
174
177
  if (!/^\d+$/.test(String(cfg[k]))) errs.push(`${k} must be a number (got "${cfg[k]}").`);
175
178
  }
@@ -237,3 +240,45 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
237
240
  export function renderProjectsTsv(cfg) {
238
241
  return projects(cfg).map((p) => `${p.name}\t${p.dir}`).join('\n') + (projects(cfg).length ? '\n' : '');
239
242
  }
243
+
244
+ /**
245
+ * Settings an agent may change from a remote session (each call needs the
246
+ * user's approval there). Secrets, capabilities, projects and service ports
247
+ * stay with `init`/`install`/`secrets` on the machine.
248
+ */
249
+ export const SETTABLE_KEYS = {
250
+ NGROK_APP_PORTS: 'comma-separated local ports that `ngrok up apps` exposes',
251
+ NGROK_APPS_PUBLIC: '1 = app tunnels without the viewer login, 0 = behind it (default)',
252
+ NGROK_DOMAIN: 'your reserved ngrok domain, or empty',
253
+ DOKPLOY_TOOL_PRESET: 'Dokploy MCP tool preset (needs install to apply)',
254
+ DOKPLOY_ENABLED_TAGS: 'Dokploy MCP tool categories to load (needs install to apply)',
255
+ DOKPLOY_DISABLED_TAGS: 'Dokploy MCP tool categories to drop (needs install to apply)',
256
+ TRANSCRIPT_DAYS: 'days Claude keeps conversation transcripts, at least 30 (needs install to apply)',
257
+ };
258
+ const NEEDS_INSTALL = /^(DOKPLOY_|TRANSCRIPT_DAYS)/;
259
+
260
+ /** Validate and save one settable key; returns { key, value, needsInstall }. */
261
+ export function setConfigValue(key, value, env = process.env) {
262
+ if (!Object.prototype.hasOwnProperty.call(SETTABLE_KEYS, key)) {
263
+ const hint = /KEY|TOKEN|SECRET|PASS/i.test(key) ? 'secrets are entered on the machine: harness-device secrets set KEY'
264
+ : 'capabilities, projects and ports change with harness-device init + install on the machine';
265
+ throw new Error(`${key} can't be changed from a session (${hint}). Settable: ${Object.keys(SETTABLE_KEYS).join(', ')}`);
266
+ }
267
+ let v = String(value ?? '').trim();
268
+ if (key === 'NGROK_APP_PORTS') v = mergePorts('', v);
269
+ if (key === 'NGROK_APPS_PUBLIC' && !['0', '1'].includes(v)) throw new Error('NGROK_APPS_PUBLIC must be 0 or 1');
270
+ if (key === 'NGROK_DOMAIN' && v && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/i.test(v)) throw new Error('NGROK_DOMAIN must be a host name such as my-app.ngrok-free.app');
271
+ const cfg = { ...loadConfig(env).cfg, [key]: v };
272
+ const errs = validateConfig(cfg, env);
273
+ if (errs.length) throw new Error(errs.join(' '));
274
+ saveConfig(cfg, env);
275
+ return { key, value: v, needsInstall: NEEDS_INSTALL.test(key) };
276
+ }
277
+
278
+ /** "3000,5173" + [8099] → "3000,5173,8099" (deduplicated, each 1-65535). */
279
+ export function mergePorts(existing, add) {
280
+ const list = [...String(existing || '').split(','), ...(Array.isArray(add) ? add : String(add || '').split(','))]
281
+ .map((x) => String(x).trim()).filter(Boolean);
282
+ for (const p of list) if (!/^\d+$/.test(p) || Number(p) < 1 || Number(p) > 65535) throw new Error(`Not a port: ${p}`);
283
+ return [...new Set(list.map(Number))].join(',');
284
+ }
package/src/device.js CHANGED
@@ -6,6 +6,8 @@ import path from 'node:path';
6
6
  import { spawn } from 'node:child_process';
7
7
  import { capture, ok, httpJson, which } from './util.js';
8
8
  import { listSessions, listProcs, recentEvents } from './state.js';
9
+ import { loadConfig, saveConfig, mergePorts } from './config.js';
10
+ import * as ngrok from './ngrok.js';
9
11
 
10
12
  const short = (u) => u.replace(/^harness-/, '');
11
13
  const logical = (name) => (name.startsWith('harness-') ? name : `harness-${name}`).replace(/\.(service|timer)$/, '');
@@ -125,3 +127,43 @@ export async function ngrokStatus() {
125
127
  if (!j) return { running: false, tunnels: [] };
126
128
  return { running: true, tunnels: (j.tunnels || []).map((t) => ({ name: t.name, url: t.public_url, addr: t.config && t.config.addr })) };
127
129
  }
130
+
131
+ /**
132
+ * Open ngrok tunnels (groups or single names), optionally adding app ports
133
+ * first. Shared by `harness-device ngrok up` and the ngrok_up MCP tool.
134
+ * Returns { tunnels, shared, missing, login } — login only for tunnels behind basic auth.
135
+ */
136
+ export async function ngrokUp(ctx, { tunnels = [], ports = [] } = {}) {
137
+ const p = ctx.paths;
138
+ if (!ctx.caps.some((c) => c.id === 'ngrok')) throw new Error('The ngrok capability is off on this device (turn it on with harness-device init --with ngrok + install, on the machine).');
139
+ if (!fs.existsSync(p.ngrokToken)) throw new Error('No ngrok authtoken on this device yet (harness-device ngrok token, on the machine).');
140
+ let { cfg } = loadConfig(ctx.env);
141
+ const file = fs.existsSync(p.config) ? fs.readFileSync(p.config, 'utf8') : '';
142
+ let dirty = !/^NGROK_VIEWER_PASS=/m.test(file); // a generated password must be saved, or the next run makes another
143
+ if (ports.length) {
144
+ const merged = mergePorts(cfg.NGROK_APP_PORTS, ports);
145
+ if (merged !== String(cfg.NGROK_APP_PORTS || '')) { cfg = { ...cfg, NGROK_APP_PORTS: merged }; dirty = true; }
146
+ }
147
+ if (dirty) saveConfig(cfg, ctx.env);
148
+ const want = tunnels.length ? tunnels : ports.length ? ports.map((x) => `app${Number(x)}`) : ['viewers'];
149
+ const names = ngrok.selectTunnels(cfg, want, ctx.platform.id);
150
+ const write = (f, body) => { fs.writeFileSync(f + '.tmp', body, { mode: 0o600 }); fs.renameSync(f + '.tmp', f); };
151
+ write(p.ngrokYml, ngrok.renderNgrokYml(cfg, fs.readFileSync(p.ngrokToken, 'utf8').trim(), ctx.platform.id));
152
+ write(p.ngrokEnv, ngrok.renderNgrokEnv(names));
153
+ ctx.platform.ngrokUp(ctx);
154
+ let s = { running: false, tunnels: [] };
155
+ for (let i = 0; i < 30; i++) {
156
+ await new Promise((r) => setTimeout(r, 1000));
157
+ s = await ngrokStatus();
158
+ if (s.tunnels.length >= names.length) break;
159
+ }
160
+ const all = Object.assign({}, ...Object.values(ngrok.tunnels(cfg, ctx.platform.id)));
161
+ const guarded = names.filter((n) => all[n] && all[n].basic_auth);
162
+ return {
163
+ running: s.running,
164
+ tunnels: s.tunnels,
165
+ shared: ngrok.sharedUrls(s.tunnels),
166
+ missing: names.filter((n) => !s.tunnels.some((t) => t.name === n)),
167
+ login: guarded.length ? { user: cfg.NGROK_VIEWER_USER, password: cfg.NGROK_VIEWER_PASS, for: guarded } : null,
168
+ };
169
+ }
package/src/install.js CHANGED
@@ -67,7 +67,7 @@ export async function install(ctx, opts = {}) {
67
67
  log.step(`Wiring capabilities into ${ctx.provider.label}`);
68
68
  const servers = allMcpServers(ctx);
69
69
  const res = ctx.provider.apply({ ...ctx, mcpServers: servers, warn: log.warn });
70
- log.info(color.dim(` MCP: ${servers.map((s) => s.name).join(', ')} · pre-approved rules: ${res.allow.length} · denied: ${res.deny.length}`));
70
+ log.info(color.dim(` MCP: ${(res.registered || servers.map((s) => s.name)).join(', ')}${res.skipped && res.skipped.length ? ` (yours kept: ${res.skipped.join(', ')})` : ''} · pre-approved rules: ${res.allow.length} · denied: ${res.deny.length}`));
71
71
 
72
72
  for (const c of ctx.caps) for (const k of c.secrets || []) if (!ctx.secrets[k]) log.warn(`${c.id}: set ${k} with: harness-device secrets set ${k}`);
73
73
  if (ctx.caps.some((c) => c.id === 'dokploy') && !ctx.cfg.DOKPLOY_URL) log.warn('dokploy: set your Dokploy URL with: harness-device init --dokploy-url https://…');
package/src/mcp/server.js CHANGED
@@ -9,13 +9,38 @@ 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';
13
15
 
14
16
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
15
17
  const fail = (e) => ({ isError: true, content: [{ type: 'text', text: String(e && e.message ? e.message : e) }] });
16
18
 
17
19
  const has = (ctx, id) => ctx.caps.some((c) => c.id === id);
18
20
 
21
+ /** Thrown when the user declines or cancels a form; reported as a plain result, not a failure. */
22
+ class Cancelled extends Error {}
23
+
24
+ /**
25
+ * Ask the user for missing details with an MCP elicitation form (rendered by
26
+ * the client: a dialog or card the remote user fills in). Without client
27
+ * support it fails with the field names, so the agent asks with its own UI.
28
+ */
29
+ async function ask(server, message, properties, required = Object.keys(properties)) {
30
+ if (!server.server.getClientCapabilities()?.elicitation) {
31
+ throw new Error(`Missing: ${Object.keys(properties).join(', ')}. Ask the user (with your interactive question tool) and call again with them.`);
32
+ }
33
+ const r = await server.server.elicitInput({ mode: 'form', message, requestedSchema: { type: 'object', properties, required } });
34
+ if (r.action !== 'accept') throw new Cancelled(`Cancelled by the user (${r.action}); nothing was changed.`);
35
+ return r.content || {};
36
+ }
37
+
38
+ /** A yes/no confirmation form; resolves only on yes. */
39
+ async function confirm(server, message) {
40
+ const a = await ask(server, message, { confirm: { type: 'boolean', title: 'Go ahead', default: true } });
41
+ if (!a.confirm) throw new Cancelled('Not confirmed by the user; nothing was changed.');
42
+ }
43
+
19
44
  export function buildServer(env = process.env) {
20
45
  const ctx = () => loadContext(env);
21
46
  const base = ctx();
@@ -25,7 +50,7 @@ export function buildServer(env = process.env) {
25
50
  try {
26
51
  return await fn(ctx(), args || {});
27
52
  } catch (e) {
28
- return fail(e);
53
+ return e instanceof Cancelled ? text(e.message) : fail(e);
29
54
  }
30
55
  });
31
56
 
@@ -39,14 +64,27 @@ export function buildServer(env = process.env) {
39
64
  async (c) => text(state.listProcs(c)));
40
65
 
41
66
  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"') },
67
+ { 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)') },
43
68
  async (c, a) => {
69
+ if (!a.dir || !a.command) {
70
+ const first = c.projects[0];
71
+ const got = await ask(server, `Details for the long-running process "${a.name}"`, {
72
+ ...(a.dir ? {} : { dir: { type: 'string', title: 'Working directory', description: 'Absolute path, usually the project folder', ...(first ? { default: first.dir } : {}) } }),
73
+ ...(a.command ? {} : { command: { type: 'string', title: 'Command', description: 'One shell line, e.g. npm run dev -- --port 5173' } }),
74
+ });
75
+ a = { ...a, ...got };
76
+ if (typeof a.dir !== 'string' || typeof a.command !== 'string' || !a.dir || !a.command) throw new Error('Both a directory and a command are needed');
77
+ }
44
78
  state.addProc(c, a.name, a.dir, a.command);
45
79
  return text(`proc ${a.name} registered; window proc-${a.name}; logs: logs tool with target "proc-${a.name}"`);
46
80
  });
47
81
 
48
82
  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) => { state.removeProc(c, a.name); return text(`proc ${a.name} removed`); });
83
+ async (c, a) => {
84
+ 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.`);
85
+ state.removeProc(c, a.name);
86
+ return text(`proc ${a.name} removed`);
87
+ });
50
88
 
51
89
  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
90
  async (c) => text({ ...device.viewers(c.cfg, c.platform), sshTunnel: device.tunnelCommand(c.cfg, c.platform), ngrok: await device.ngrokStatus() }));
@@ -99,10 +137,50 @@ export function buildServer(env = process.env) {
99
137
  }
100
138
 
101
139
  if (has(base, 'ngrok')) {
102
- tool('ngrok_status', 'Public ngrok URLs currently open on this device (tunnels are opened by the user only).', {},
140
+ tool('ngrok_status', 'Public ngrok URLs currently open on this device.', {},
103
141
  async () => text(await device.ngrokStatus()));
142
+ 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.',
143
+ { 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() },
144
+ async (c, a) => {
145
+ let tunnels = a.tunnels || [];
146
+ let ports = a.ports || [];
147
+ if (!tunnels.length && !ports.length) {
148
+ const names = Object.keys(Object.assign({}, ...Object.values(ngrok.tunnels(c.cfg, c.platform.id))));
149
+ const got = await ask(server, 'What should get a public URL?', {
150
+ tunnel: { type: 'string', title: 'Tunnel', enum: [...names, 'app port'], description: 'An existing tunnel, or "app port" for a local server' },
151
+ port: { type: 'integer', title: 'App port', minimum: 1, maximum: 65535, description: 'Only for "app port", e.g. 3000' },
152
+ }, ['tunnel']);
153
+ if (got.tunnel === 'app port') {
154
+ if (!got.port) throw new Error('No port given');
155
+ ports = [got.port];
156
+ } else tunnels = [got.tunnel];
157
+ }
158
+ return text(await device.ngrokUp(c, { tunnels, ports }));
159
+ });
160
+ tool('ngrok_down', 'Close every ngrok tunnel on this device.', {},
161
+ async (c) => {
162
+ if (server.server.getClientCapabilities()?.elicitation) await confirm(server, 'Close every public ngrok URL on this device?');
163
+ c.platform.ngrokDown(c);
164
+ return text('ngrok tunnels closed');
165
+ });
104
166
  }
105
167
 
168
+ tool('config_get', `Current device settings that can be changed with config_set: ${Object.keys(SETTABLE_KEYS).join(', ')}.`, {},
169
+ async (c) => text(Object.fromEntries(Object.keys(SETTABLE_KEYS).map((k) => [k, c.cfg[k] ?? '']))));
170
+ 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.`,
171
+ { key: z.enum(Object.keys(SETTABLE_KEYS)).optional(), value: z.string().max(200).optional() },
172
+ async (c, a) => {
173
+ if (!a.key || a.value === undefined) {
174
+ const got = await ask(server, 'Change a device setting', {
175
+ ...(a.key ? {} : { key: { type: 'string', title: 'Setting', enum: Object.keys(SETTABLE_KEYS), description: Object.entries(SETTABLE_KEYS).map(([k, d]) => `${k}: ${d}`).join('; ') } }),
176
+ value: { type: 'string', title: 'Value', maxLength: 200, ...(a.key ? { description: SETTABLE_KEYS[a.key] } : {}) },
177
+ });
178
+ a = { ...a, ...got };
179
+ if (!Object.prototype.hasOwnProperty.call(SETTABLE_KEYS, a.key)) throw new Error(`Unknown setting ${a.key}`);
180
+ }
181
+ return text(setConfigValue(a.key, String(a.value ?? ''), env));
182
+ });
183
+
106
184
  return server;
107
185
  }
108
186
 
package/src/ngrok.js CHANGED
@@ -34,9 +34,11 @@ export function tunnels(cfg, platformId = 'linux') {
34
34
  export function selectTunnels(cfg, groups, platformId = 'linux') {
35
35
  const all = tunnels(cfg, platformId);
36
36
  const list = groups.includes('all') ? GROUPS : groups;
37
- const bad = list.filter((g) => !GROUPS.includes(g));
38
- if (bad.length) throw new Error(`Unknown ngrok group: ${bad.join(', ')} (use ${GROUPS.join(', ')} or all)`);
39
- const names = list.flatMap((g) => Object.keys(all[g]));
37
+ // A group (viewers, apps, ...) or a single tunnel by name (ttyd, pwui, app3000, ...).
38
+ const single = Object.assign({}, ...GROUPS.map((g) => all[g]));
39
+ const bad = list.filter((g) => !GROUPS.includes(g) && !single[g]);
40
+ if (bad.length) throw new Error(`Unknown ngrok group or tunnel: ${bad.join(', ')} (use ${GROUPS.join(', ')}, all, or one of ${Object.keys(single).join(', ')})`);
41
+ const names = [...new Set(list.flatMap((g) => (GROUPS.includes(g) ? Object.keys(all[g]) : [g])))];
40
42
  if (!names.length) throw new Error(list.includes('apps') ? 'No app ports: set NGROK_APP_PORTS=3000,5173 in config.env' : 'Nothing to expose');
41
43
  return names;
42
44
  }
@@ -60,3 +62,10 @@ export function renderNgrokYml(cfg, authtoken, platformId = 'linux') {
60
62
  export function renderNgrokEnv(names) {
61
63
  return `HD_NGROK_TUNNELS='${names.join(' ')}'\n`;
62
64
  }
65
+
66
+ /** Names of tunnels that ended up on the same public URL (free plans have one domain). */
67
+ export function sharedUrls(tunnels) {
68
+ const by = {};
69
+ for (const t of tunnels) (by[t.url] = by[t.url] || []).push(t.name);
70
+ return Object.values(by).filter((n) => n.length > 1).flat();
71
+ }
@@ -182,12 +182,16 @@ export function followLogsCmd(u, ctx) {
182
182
  export function ngrokUp(ctx) {
183
183
  const file = path.join(serviceDir(ctx.env), plistName('harness-ngrok'));
184
184
  writeFile(file, plist(jobs(ctx)('harness-ngrok')));
185
- lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
185
+ const l = labelOf('harness-ngrok');
186
+ if (loaded(l)) {
187
+ lc(['bootout', `${domain()}/${l}`]);
188
+ for (let i = 0; i < 25 && loaded(l); i++) sleepMs(200);
189
+ }
186
190
  lc(['bootstrap', domain(), file]);
187
191
  }
188
192
 
189
193
  export function ngrokDown(ctx) {
190
- lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
194
+ if (loaded(labelOf('harness-ngrok'))) lc(['bootout', `${domain()}/${labelOf('harness-ngrok')}`]);
191
195
  fs.rmSync(path.join(serviceDir(ctx.env), plistName('harness-ngrok')), { force: true });
192
196
  }
193
197
 
@@ -100,6 +100,23 @@ function readJson(file, fallback) {
100
100
  }
101
101
  }
102
102
 
103
+ /**
104
+ * How this provider lets the agent ask the remote user with interactive UI.
105
+ * Every provider fills the same shape; the skill/instructions take guidance()
106
+ * from here, and the device's MCP tools use elicitation when the client has it.
107
+ */
108
+ export const interaction = {
109
+ askTool: 'AskUserQuestion',
110
+ supportsElicitation: true,
111
+ guidance: () => `## Asking the user
112
+ The user usually drives this session remotely (phone, claude.ai) and answers by tapping, so ask with interactive prompts, not prose:
113
+ - **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.
114
+ - 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.
115
+ - 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.
116
+ - Never tell the user to run commands on the machine. Ask with options, then do it yourself through the tools.
117
+ - 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.`,
118
+ };
119
+
103
120
  export function renderSkill({ cfg, caps, projects, platform }) {
104
121
  const head = `---
105
122
  name: harness-device
@@ -113,7 +130,7 @@ This machine is a harness device: a dev environment kept running for remote agen
113
130
  Projects on this device: ${projects.map((p) => `\`${p.name}\` (${p.dir})`).join(', ') || 'none yet'}.
114
131
  Device controls are available both as the \`harness-device\` MCP tools and as the \`harness-device\` CLI.
115
132
  `;
116
- return head + '\n' + caps.map((c) => (c.docs ? c.docs(cfg, platform) : '')).filter(Boolean).join('\n\n') + '\n';
133
+ return head + '\n' + [interaction.guidance(cfg), ...caps.map((c) => (c.docs ? c.docs(cfg, platform) : ''))].filter(Boolean).join('\n\n') + '\n';
117
134
  }
118
135
 
119
136
  export function renderClaudeMd({ cfg }) {
@@ -130,17 +147,30 @@ export function userMcpServers(env) {
130
147
  // harness-device MCP tools that only read, or restart the browser. proc_add,
131
148
  // proc_remove, restart_service and playwright_ui still ask: they start or stop things.
132
149
  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}`);
150
+ 'browser_restart', 'screenshot', 'run_tests_live', 'docker_summary', 'ngrok_status', 'config_get'].map((t) => `mcp__harness-device__${t}`);
134
151
 
135
152
  /**
136
153
  * A Read() rule for an absolute path. In Claude Code rules `/x` is relative to
137
154
  * the settings file; `~/x` is under home and `//x` is absolute.
138
155
  */
139
156
  export function readRule(abs, home) {
157
+ return pathRule('Read', abs, home);
158
+ }
159
+
160
+ /** A path rule (Read, Edit) for an absolute path; see readRule. */
161
+ export function pathRule(tool, abs, home) {
140
162
  const rel = path.relative(home, abs);
141
- return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? `Read(~/${rel})` : `Read(/${abs})`;
163
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? `${tool}(~/${rel})` : `${tool}(/${abs})`;
142
164
  }
143
165
 
166
+ /**
167
+ * Commands that change the device's own install. A session changes the device
168
+ * only through harness-device tools the user approves there (config_set,
169
+ * ngrok_up, proc_add, ...), never by hand.
170
+ */
171
+ export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-device install:*)',
172
+ 'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)'];
173
+
144
174
  /**
145
175
  * Wire everything into Claude Code. ctx: { cfg, caps, projects, paths, env, dryRun, mcpServers }
146
176
  */
@@ -183,6 +213,9 @@ export function apply(ctx) {
183
213
  readRule(path.join(paths.home, 'secrets.env'), home),
184
214
  readRule(path.join(paths.home, 'ngrok*'), home),
185
215
  readRule(path.join(home, '.ssh', '**'), home),
216
+ // The Edit rule covers every file-writing tool: the device home changes only through harness-device.
217
+ pathRule('Edit', path.join(paths.home, '**'), home),
218
+ ...DEVICE_ADMIN_DENY,
186
219
  ]))];
187
220
  const { settings, added } = mergePermissions(readJson(f.settings, {}), { allow, deny }, prev);
188
221
  // Restores resume conversations from their transcripts, so Claude Code
@@ -190,7 +223,7 @@ export function apply(ctx) {
190
223
  const keep = applyRetention(settings, Number(ctx.cfg.TRANSCRIPT_DAYS), prev);
191
224
  writeFile(f.settings, JSON.stringify(settings, null, 2) + '\n', { dryRun });
192
225
  writeFile(stateFile, JSON.stringify({ ...added, ...keep, mcp: mcpNames }, null, 2) + '\n', { dryRun });
193
- return { allow, deny, added };
226
+ return { allow, deny, added, registered: mcpNames, skipped: foreign };
194
227
  }
195
228
 
196
229
  export function remove(ctx) {