@dreamtree-org/harness-device 0.9.1 → 0.9.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/README.md CHANGED
@@ -207,6 +207,7 @@ Repositories this device runs, kept in `APPS_DIR` (default `~/apps`). Unlike pro
207
207
  | `file_read` / `file_write` | Inside the app folder only; `.git` and `.env` are off limits |
208
208
  | `env_manage` | The app's `.env`. `list` shows names only. `set` takes a value or `from_secret` (copies a device secret without exposing it), and asks first |
209
209
  | `exec` | One program with an argv and no shell. The program must be on `EXEC_ALLOW` (a default list of dev tools); shells and wrappers such as `bash`, `env`, `sudo` or `xargs` are always refused. Runs in the app folder or a confined sub-folder. `env_refs` injects device secrets by name and redacts them from output. Timeout and output cap (head and tail kept). A durable job: `job_status` with `offset` streams new output, `job_cancel` kills the whole process tree. Never restarted. Linux holds the per-process caps in a systemd scope; on macOS the watchdog covers running jobs. Each run is recorded in `events` (program, folder, outcome, exit code, duration; never env or output) |
210
+ | `app_remove` | Removes a managed app (asks first; CLI `harness-device app rm <app> [--force]`): stops its process and previews, archives its workspaces, deletes its folder and forgets its record, port and code graph. It refuses while the app holds work found nowhere else (uncommitted or untracked files, commits on no remote, workspaces) unless `discard_changes` is set after the user agrees. Session projects and folders outside `APPS_DIR` are never deleted |
210
211
  | `workspace_create` / `workspace_list` / `workspace_status` / `workspace_archive` | Per-ticket workspaces of a cloned app. Each is a git worktree under `APPS_DIR/.worktrees/<app>/<ticket>` on branch `ticket/<TICKET>`, created from a pinned revision (`base`, default `origin/<branch>`; the SHA is recorded). It gets its own port (4100–4999, kept across retries) and is registered as the app `<app>--<ticket>`, so every app tool works on it. Creating it again returns the same workspace. Git operations on one repository are serialized by a lock. Archiving stops its process, removes the folder, frees the port and keeps the branch; uncommitted changes make it refuse unless the user agrees to discard them. `REPO_ALLOW` (owner/repo, owner/*) limits which repositories `git_clone` and workspaces accept. Per-workspace databases (`database: true`) answer BLOCKED until the shared development DB provisioner exists; no local database container is started instead |
211
212
  | `preview_start` / `preview_list` / `preview_stop` / `preview_screenshot` | Protected previews of an app or workspace. Starts its dev server on its own port if nothing answers there and health-checks it; on failure it returns the app's last output and stops it. A per-preview proxy listens on 127.0.0.1 only and forwards to that one app port. Every request needs a token bound to the preview and its expiry, signed with a device key (`state/preview.key`). The link sets an HttpOnly cookie. The record is checked on each request, so a stopped preview is refused at once, and WebSocket upgrades are checked too. Reach it with the SSH tunnel command it returns. A public ngrok URL is opt-in (`public: true`, user-approved) and still needs the token. `preview_stop` revokes the link, stops the proxy, closes the tunnel and stops the app if the preview started it. Expired previews, and previews whose app or proxy is gone, are ended by `preview_list` and by every watchdog pass (`limits --enforce`). `preview_screenshot` (browser capability) loads it in the device browser and returns a PNG; `save: true` also keeps it in the app's `.dreamtree/evidence/captures/` for ai-builder's `evidence add screenshot` |
212
213
  | `shell_exec` (`app exec <app> -- <cmd>`) | One command in the app folder: up to 120s inline, otherwise as a job. Through the pool it needs `device:admin` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.9.1",
3
+ "version": "0.9.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/cli.js CHANGED
@@ -57,7 +57,7 @@ ${color.bold('Device')}
57
57
  join <hub-url> --enroll <secret> join a HarnessPro pool (the dashboard's install command runs this)
58
58
  leave leave the pool and forget its credential
59
59
  pool [status] pool hub, link state, POOL_SCOPES; \`pool link\` is the service
60
- app list | clone <url> [--name N] [--branch B] | pull|setup|start|stop|deploy <app> | exec <app> -- <cmd>
60
+ app list | clone <url> [--name N] [--branch B] | pull|setup|start|stop|deploy <app> | exec <app> -- <cmd> | rm <app> [--force]
61
61
  managed apps in APPS_DIR (~/apps): clone, install, run, update (jobs run in the background)
62
62
  job list | job <id> | job run <id> background jobs (clone, setup, deploy) and their logs
63
63
  limits [--enforce] [--json] safe maximums (RAM reserve, per process, browser, sessions) and current use; --enforce runs one watchdog pass
@@ -335,8 +335,9 @@ export async function main(argv) {
335
335
  if (['pull', 'setup', 'deploy'].includes(sub)) return out(await pr[sub](ctx, { app: rest[0] }));
336
336
  if (sub === 'start') return out(pr.start(ctx, { app: rest[0], command: f.command, port: f.port, restart: !!f.restart }));
337
337
  if (sub === 'stop') return out(pr.stop(ctx, { app: rest[0] }));
338
+ if (sub === 'rm' || sub === 'remove') return out(await (await import('./remove.js')).removeApp(ctx, { name: rest[0], force: !!f.force }));
338
339
  if (sub === 'exec') return out(await pr.shellExec(ctx, { app: rest[0], command: rest.slice(1).join(' '), timeoutSeconds: f.timeout }));
339
- throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec');
340
+ throw new Error('usage: harness-device app list|clone|pull|setup|start|stop|deploy|exec|rm <app> [--force]');
340
341
  }
341
342
 
342
343
  case 'preview': {
package/src/device.js CHANGED
@@ -188,6 +188,9 @@ export async function ngrokUp(ctx, { tunnels = [], ports = [] } = {}) {
188
188
  tunnels: s.tunnels,
189
189
  shared: ngrok.sharedUrls(s.tunnels),
190
190
  missing: names.filter((n) => !s.tunnels.some((t) => t.name === n)),
191
+ ...(names.some((n) => !s.tunnels.some((t) => t.name === n))
192
+ ? { error: `${s.running ? 'ngrok runs but' : 'ngrok did not start, so'} ${names.filter((n) => !s.tunnels.some((t) => t.name === n)).join(', ')} did not open within 30s; see logs svc-ngrok (harness-device logs ngrok). A free ngrok plan allows one URL at a time.` }
193
+ : {}),
191
194
  login: guarded.length ? { user: cfg.NGROK_VIEWER_USER, password: cfg.NGROK_VIEWER_PASS, for: guarded } : null,
192
195
  };
193
196
  }
package/src/mcp/server.js CHANGED
@@ -22,6 +22,7 @@ import * as execMod from '../exec.js';
22
22
  import * as ws from '../workspace.js';
23
23
  import * as preview from '../preview.js';
24
24
  import { getApp } from '../apps.js';
25
+ import * as removal from '../remove.js';
25
26
  import { Cancelled, NeedsUser, interaction } from './interact.js';
26
27
 
27
28
  const text = (v) => ({ content: [{ type: 'text', text: typeof v === 'string' ? v : JSON.stringify(v, null, 2) }] });
@@ -120,6 +121,15 @@ export function buildServer(env = process.env, opts = {}) {
120
121
  tool('app_list', 'Managed apps on this device (cloned with git_clone): folder, repo and branch, detected stack, start command and port, and whether its process runs.', {},
121
122
  async (c) => text(project.list(c)));
122
123
 
124
+ tool('app_remove', 'Remove a managed app (asks the user first): stops its process and previews, archives its workspaces, deletes its folder in the apps folder and forgets its record, port and code graph. Refuses while it holds work found nowhere else (uncommitted or untracked files, commits on no remote, workspaces) unless discard_changes=true after the user agrees to lose it. Session projects and folders outside the apps folder are never deleted.',
125
+ { app: APP, discard_changes: z.boolean().optional(), ...CONFIRM },
126
+ async (c, a, u) => {
127
+ const p = removal.removalPlan(c, a.app);
128
+ if (!p.safe && !a.discard_changes) return { isError: true, content: [{ type: 'text', text: `${removal.describePlan(p).replace(/^Remove app \S+\? /, `${a.app} was not removed. `)} Push or archive that work first, or call again with discard_changes=true after the user agrees to lose it.` }] };
129
+ await u.confirm(removal.describePlan(p));
130
+ return text(await removal.removeApp(c, { name: a.app, force: !!a.discard_changes }));
131
+ });
132
+
123
133
  tool('git_clone', 'Clone a repository into the apps folder as a managed app, then detect its stack (job). Private GitHub repos use the device secret GITHUB_TOKEN (or token_secret), passed to git through the environment only. No agent session unless session=true. Next: project_setup, then project_start.',
124
134
  { url: z.string().max(300).describe('https://host/owner/repo(.git), git@host:owner/repo, or file:///path'), name: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/).optional(), branch: z.string().max(100).optional(),
125
135
  token_secret: z.string().regex(/^[A-Z][A-Z0-9_]{0,63}$/).optional().describe('device secret holding a git token (default GITHUB_TOKEN for github.com)'), session: z.boolean().optional().describe('also give it a persistent agent session'), ...FORCE },
@@ -190,7 +190,11 @@ export function ngrokUp(ctx) {
190
190
  lc(['bootout', `${domain()}/${l}`]);
191
191
  for (let i = 0; i < 25 && loaded(l); i++) sleepMs(200);
192
192
  }
193
- lc(['bootstrap', domain(), file]);
193
+ // `harness-device stop` disables every job (ngrok too) and `start` brings back
194
+ // only the always-on ones, so enable it here or launchd refuses to load it
195
+ // (bootstrap: 5 Input/output error).
196
+ lc(['enable', `${domain()}/${l}`]);
197
+ bootstrap(file, l, { dryRun: false });
194
198
  }
195
199
 
196
200
  export function ngrokDown(ctx) {
@@ -272,6 +276,8 @@ export function stopServices(ctx, { persist = false, dryRun = false } = {}) {
272
276
  /** Enable and load every harness job again (tmux first, heal last). */
273
277
  export function startServices(ctx, { dryRun = false } = {}) {
274
278
  const dir = serviceDir(ctx.env);
279
+ // ngrok runs on demand (ngrok_up), so it is not loaded here; but stop disabled it, so enable it again.
280
+ lc(['enable', `${domain()}/${labelOf('harness-ngrok')}`], { dryRun });
275
281
  for (const u of [...STOP_ORDER(ctx.units)].reverse()) {
276
282
  const l = labelOf(u);
277
283
  lc(['enable', `${domain()}/${l}`], { dryRun });
package/src/preview.js CHANGED
@@ -160,11 +160,14 @@ export async function startPreview(ctx, { app: name, ttlMinutes = 60, healthSeco
160
160
  if (!(await waitPort(proxyPort, 15))) { await stopPreview(ctx, { id, reason: 'proxy did not start', stopApp: startedApp }); throw new Error(`The preview proxy did not start (logs: proc-preview-${id})`); }
161
161
  }
162
162
  if (pub) {
163
- const r = await (publish || defaultPublish)(ctx, proxyPort);
164
- savePreview(ctx, { ...getPreview(ctx, id), public: true, publicUrl: r.url || null });
163
+ let r;
164
+ try { r = await (publish || defaultPublish)(ctx, proxyPort); } catch (e) { r = { url: null, error: e.message }; }
165
+ // Public only with a URL: a preview never claims a tunnel it does not have.
166
+ savePreview(ctx, { ...getPreview(ctx, id), public: !!r.url, publicUrl: r.url || null, publicError: r.url ? null : (r.error || 'no public URL') });
165
167
  }
166
- state.event(ctx, `preview ${id} of ${app.name}: app port ${port}, proxy ${proxyPort}, expires ${expiresAt}${pub ? ', public URL opened' : ''}`);
167
- return link(ctx, getPreview(ctx, id));
168
+ const saved = getPreview(ctx, id);
169
+ state.event(ctx, `preview ${id} of ${app.name}: app port ${port}, proxy ${proxyPort}, expires ${expiresAt}${pub ? (saved.public ? ', public URL opened' : `, public URL FAILED: ${saved.publicError}`) : ''}`);
170
+ return link(ctx, saved);
168
171
  }
169
172
 
170
173
  /** The links for a preview (a fresh token valid until the preview expires). */
@@ -175,6 +178,7 @@ export function link(ctx, rec) {
175
178
  url: `http://127.0.0.1:${rec.proxyPort}/?${PARAM}=${token}`,
176
179
  ssh_tunnel: `ssh -N -L ${rec.proxyPort}:127.0.0.1:${rec.proxyPort} <user>@<this-machine> (then open the url on your computer)`,
177
180
  ...(rec.publicUrl ? { public_url: `${rec.publicUrl}/?${PARAM}=${token}` } : {}),
181
+ ...(rec.publicError ? { public_error: `No public URL: ${rec.publicError}. The preview works locally (url / ssh_tunnel); preview_stop it and retry public once ngrok is fixed.` } : {}),
178
182
  };
179
183
  }
180
184
 
@@ -182,7 +186,7 @@ async function defaultPublish(ctx, port) {
182
186
  const device = await import('./device.js');
183
187
  const r = await device.ngrokUp(ctx, { ports: [port] });
184
188
  const t = r.tunnels.find((x) => String(x.addr || '').endsWith(`:${port}`) || x.name === `app${port}`);
185
- return { url: t ? t.url : null };
189
+ return { url: t ? t.url : null, error: t ? null : (r.error || 'the ngrok tunnel did not open') };
186
190
  }
187
191
 
188
192
  async function defaultUnpublish(ctx, stillPublic) {
package/src/remove.js ADDED
@@ -0,0 +1,72 @@
1
+ // Removing a managed app (app_remove / `harness-device app rm`).
2
+ //
3
+ // The reverse of git_clone: stops what runs for the app (its process and its
4
+ // previews), archives its workspaces, deletes its folder and forgets its
5
+ // record, port and code graph. Only apps cloned into the apps folder can be
6
+ // removed: session projects and folders elsewhere are never deleted.
7
+ //
8
+ // Work that exists nowhere else blocks it unless `force`: uncommitted or
9
+ // untracked files, commits not on any remote, and workspaces (their ticket
10
+ // branches live in the app's repository and go with it).
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { appsDir, getApp, procName } from './apps.js';
16
+ import { listWorkspaces, archiveWorkspace, releasePort } from './workspace.js';
17
+ import { listPreviews, stopPreview } from './preview.js';
18
+ import * as state from './state.js';
19
+
20
+ const git = (dir, args) => {
21
+ const r = spawnSync('git', args, { cwd: dir, encoding: 'utf8' });
22
+ return r.status === 0 ? r.stdout.trim() : null;
23
+ };
24
+ const lines = (s) => (s ? s.split('\n').filter(Boolean) : []);
25
+
26
+ /** What removing `name` would lose, and whether it may be removed at all. */
27
+ export function removalPlan(ctx, name) {
28
+ const app = getApp(ctx, name);
29
+ if (app.project) throw new Error(`${name} is a session project, not a managed app: it is never removed by app_remove (harness-device project rm unregisters it, keeping its folder)`);
30
+ if (app.workspace) throw new Error(`${name} is a workspace: use workspace_archive`);
31
+ const root = fs.realpathSync(appsDir(ctx));
32
+ let dir = null;
33
+ if (fs.existsSync(app.dir)) {
34
+ dir = fs.realpathSync(app.dir);
35
+ if (!dir.startsWith(root + path.sep)) throw new Error(`${name}'s folder ${app.dir} is outside the apps folder (${root}); it is not deleted by app_remove`);
36
+ }
37
+ const isGit = dir && git(dir, ['rev-parse', '--is-inside-work-tree']) === 'true';
38
+ const dirty = isGit ? lines(git(dir, ['status', '--porcelain'])).map((l) => l.slice(3)) : [];
39
+ const unpushed = isGit ? lines(git(dir, ['log', '--branches', '--not', '--remotes', '--format=%h %s'])) : [];
40
+ const workspaces = listWorkspaces(ctx, name).map((w) => w.name);
41
+ const previews = listPreviews(ctx).filter((p) => p.status === 'active' && p.app === name).map((p) => p.id);
42
+ const running = state.listProcs(ctx).some((p) => p.name === procName(app));
43
+ return { name, dir: app.dir, exists: !!dir, git: !!isGit, dirty, unpushed, workspaces, previews, running, safe: !dirty.length && !unpushed.length && !workspaces.length };
44
+ }
45
+
46
+ /** One line for the confirmation question. */
47
+ export function describePlan(p) {
48
+ const lost = [
49
+ p.dirty.length && `${p.dirty.length} uncommitted/untracked file(s) (${p.dirty.slice(0, 5).join(', ')}${p.dirty.length > 5 ? ', …' : ''})`,
50
+ p.unpushed.length && `${p.unpushed.length} commit(s) on no remote (${p.unpushed.slice(0, 3).join('; ')}${p.unpushed.length > 3 ? '; …' : ''})`,
51
+ p.workspaces.length && `workspace(s) ${p.workspaces.join(', ')} and their ticket branches`,
52
+ ].filter(Boolean);
53
+ return `Remove app ${p.name}? Its folder ${p.dir} is deleted${p.running ? ', its process stopped' : ''}${p.previews.length ? `, ${p.previews.length} preview(s) stopped` : ''}, and its record, port and code graph forgotten.${lost.length ? ` LOST for good: ${lost.join('; ')}.` : ' Everything in it is on its remote.'}`;
54
+ }
55
+
56
+ export async function removeApp(ctx, { name, force = false }) {
57
+ const p = removalPlan(ctx, name);
58
+ if (!p.safe && !force) {
59
+ throw Object.assign(new Error(`${describePlan(p).replace(/^Remove app \S+\? /, `${name} was not removed. `)} Push or archive that work first, or remove with force once the user agrees to lose it.`), { code: 'NOT_SAFE', plan: p });
60
+ }
61
+ const app = getApp(ctx, name);
62
+ for (const id of p.previews) await stopPreview(ctx, { id, reason: 'app removed' }).catch(() => {});
63
+ for (const w of p.workspaces) await archiveWorkspace(ctx, { name: w, force: true });
64
+ if (p.running) state.removeProc(ctx, procName(app));
65
+ if (p.exists) fs.rmSync(app.dir, { recursive: true, force: true });
66
+ releasePort(ctx, name);
67
+ fs.rmSync(path.join(ctx.paths.state, 'graphs', name), { recursive: true, force: true });
68
+ fs.rmSync(path.join(ctx.paths.state, 'apps', `${name}.json`), { force: true });
69
+ const lost = force && !p.safe ? ` (forced: ${p.dirty.length} uncommitted file(s), ${p.unpushed.length} unpushed commit(s), ${p.workspaces.length} workspace(s) discarded)` : '';
70
+ state.event(ctx, `app ${name} removed: folder ${p.dir} deleted${lost}`);
71
+ return { removed: name, dir: p.dir, stopped: { process: p.running, previews: p.previews }, archived_workspaces: p.workspaces, discarded: force ? { dirty: p.dirty, unpushed: p.unpushed } : { dirty: [], unpushed: [] } };
72
+ }
@@ -15,7 +15,7 @@ const TOOLS = {
15
15
  'app_list', 'file_read', 'job_status', 'workspace_list', 'workspace_status', 'preview_list', 'preview_screenshot',
16
16
  'graph_status', 'graph_query', 'graph_summary'],
17
17
  'device:operate': ['proc_add', 'proc_remove', 'session_new', 'restart_service', 'browser_restart', 'run_tests_live', 'playwright_ui', 'ngrok_up', 'ngrok_down', 'disk_cleanup', 'docker_limit',
18
- 'git_clone', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
18
+ 'git_clone', 'app_remove', 'git_pull', 'project_setup', 'project_start', 'project_stop', 'project_deploy', 'file_write', 'env_manage',
19
19
  'exec', 'job_submit', 'job_cancel', 'graph_index', 'workspace_create', 'workspace_archive', 'preview_start', 'preview_stop'],
20
20
  // shell_exec is not listed: it needs device:admin (unknown tools do).
21
21
  };