@dreamtree-org/harness-device 0.1.2 → 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 +12 -0
- package/README.md +10 -5
- package/package.json +1 -1
- package/src/capabilities.js +11 -3
- package/src/cli.js +32 -24
- package/src/config.js +42 -0
- package/src/device.js +42 -0
- package/src/mcp/server.js +82 -4
- package/src/providers/claude.js +36 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
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
|
+
|
|
3
15
|
## 0.1.2
|
|
4
16
|
|
|
5
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.
|
package/README.md
CHANGED
|
@@ -146,7 +146,8 @@ Run `install` again with the new version: `npx @dreamtree-org/harness-device@lat
|
|
|
146
146
|
| `restart <service>` | Restart one harness service |
|
|
147
147
|
| `tunnel` | The SSH command for the viewers |
|
|
148
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 |
|
|
149
|
-
| `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) |
|
|
150
151
|
| `mcp` | The harness-device MCP server (stdio) |
|
|
151
152
|
| `fleet add <name> <user@host>`, `fleet status`, `fleet run <name> <args>` | Many devices from one machine, over ssh |
|
|
152
153
|
| `uninstall [--purge]` | Remove services and agent wiring (`--purge` also deletes state and config) |
|
|
@@ -176,9 +177,13 @@ Extra MCP servers for the agent: add `MCP_<name>=command args` lines to `config.
|
|
|
176
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.
|
|
177
178
|
|
|
178
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.
|
|
179
|
-
- **Denied:** `sudo`, `su`, shutdown/reboot, `mkfs`, `dd`, `rm -rf` of `/` or home, `tmux kill-server`/`kill-session`,
|
|
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`.
|
|
180
181
|
- **Never from inside a session:** restarting tmux (it holds every live session); the MCP tool refuses it, and the CLI asks for `--force`.
|
|
181
|
-
- **Everything else asks you**, including Dokploy deploys, registering or removing processes (`
|
|
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.
|
|
182
187
|
|
|
183
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.
|
|
184
189
|
|
|
@@ -203,7 +208,7 @@ harness-device fleet status # every device: sessions, failing slots, serv
|
|
|
203
208
|
|
|
204
209
|
## Security
|
|
205
210
|
|
|
206
|
-
- 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
|
|
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).
|
|
207
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.
|
|
208
213
|
- `docker` access is root-equivalent on Linux. Leave the `docker` capability off on a device you share.
|
|
209
214
|
|
|
@@ -223,7 +228,7 @@ Logs: `harness-device logs <project|proc-name|service> [-f]`.
|
|
|
223
228
|
## What it deliberately does NOT do
|
|
224
229
|
|
|
225
230
|
- **Install Dokploy, or any server software beyond the tools above.** Dokploy is used through the API of your existing deployment.
|
|
226
|
-
- **Open public URLs on its own.** ngrok stays off until you
|
|
231
|
+
- **Open public URLs on its own.** ngrok stays off until you open a tunnel or approve the agent's `ngrok_up` request.
|
|
227
232
|
- **Replace a conversation silently.** A failing slot is flagged; only `session reset` starts a new one.
|
|
228
233
|
- **Sandbox the agent.** It runs as your user, with the approvals above.
|
|
229
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.
|
|
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",
|
package/src/capabilities.js
CHANGED
|
@@ -75,7 +75,15 @@ ${cfg.SERVE_MODE === 'server'
|
|
|
75
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).
|
|
76
76
|
- Docker containers you start: use \`--restart unless-stopped\` (compose: \`restart: unless-stopped\`) so they come back after a reboot.
|
|
77
77
|
- \`harness-device status\` shows sessions, processes and services; \`harness-device events\` shows what was restored after the last restart.
|
|
78
|
-
- \`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.`,
|
|
79
87
|
},
|
|
80
88
|
|
|
81
89
|
system: {
|
|
@@ -107,7 +115,7 @@ ${cfg.SERVE_MODE === 'server'
|
|
|
107
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}\`.
|
|
108
116
|
- Screenshot of the screen: the \`screenshot\` MCP tool, or \`screencapture -x /tmp/screen.png\`.`
|
|
109
117
|
: `## Display and live viewers
|
|
110
|
-
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
|
|
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.
|
|
111
119
|
- Anything headed you start (browsers, Electron, Playwright \`--headed\`) appears there, so the user can see progress.
|
|
112
120
|
- Screenshot of the whole display: the \`screenshot\` MCP tool, or \`import -display :${cfg.DISPLAY_NUM} -window root /tmp/screen.png\`.`,
|
|
113
121
|
},
|
|
@@ -201,7 +209,7 @@ Deployments go through the user's Dokploy at ${cfg.DOKPLOY_URL || '(DOKPLOY_URL
|
|
|
201
209
|
{ name: 'ngrok authtoken', ok: fs.existsSync(ctx.paths.ngrokToken), warn: true, fix: 'harness-device ngrok token' },
|
|
202
210
|
],
|
|
203
211
|
docs: () => `## ngrok
|
|
204
|
-
Public URLs are off by default.
|
|
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.`,
|
|
205
213
|
},
|
|
206
214
|
|
|
207
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
|
-
|
|
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,27 +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
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
if (
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
ctx.platform.ngrokUp(ctx);
|
|
336
|
-
// The agent needs a few seconds to connect; wait for every tunnel (up to 30 s).
|
|
337
|
-
let s = { running: false, tunnels: [] };
|
|
338
|
-
for (let i = 0; i < 30; i++) {
|
|
339
|
-
await new Promise((r) => setTimeout(r, 1000));
|
|
340
|
-
s = await device.ngrokStatus();
|
|
341
|
-
if (s.tunnels.length >= names.length) break;
|
|
342
|
-
}
|
|
343
|
-
for (const t of s.tunnels) console.log(` ${t.name.padEnd(10)} ${color.bold(t.url)} → ${t.addr}`);
|
|
344
|
-
const shared = ngrok.sharedUrls(s.tunnels);
|
|
345
|
-
if (shared.length) log.warn(`Your ngrok plan gives one URL, so ${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.`);
|
|
346
|
-
if (s.running && s.tunnels.length < names.length) log.warn(`only ${s.tunnels.length} of ${names.length} tunnels are up yet; check: harness-device ngrok status, harness-device logs ngrok`);
|
|
347
|
-
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})`));
|
|
348
|
-
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');
|
|
349
357
|
}
|
|
350
358
|
if (sub === 'down') {
|
|
351
359
|
ctx.platform.ngrokDown(ctx);
|
package/src/config.js
CHANGED
|
@@ -240,3 +240,45 @@ export function renderRuntimeEnv(cfg, env = process.env, { units = [], platformI
|
|
|
240
240
|
export function renderProjectsTsv(cfg) {
|
|
241
241
|
return projects(cfg).map((p) => `${p.name}\t${p.dir}`).join('\n') + (projects(cfg).length ? '\n' : '');
|
|
242
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/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) => {
|
|
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
|
|
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/providers/claude.js
CHANGED
|
@@ -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) ?
|
|
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
|