@dreamtree-org/harness-device 0.1.4 → 0.1.6

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,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.6
4
+
5
+ - **Upgrade from a remote session, on any install.** The `upgrade` tool (you approve it) now also works on devices that run from a source folder: it applies the folder's current code. By default it then restarts the device gracefully, so every session, the asking one included, loads the new tools and resumes its conversation. CLI: `harness-device upgrade --apply [--restart] [--detach]`; `upgrade --restart` does the same after an npm upgrade.
6
+
7
+ ## 0.1.5
8
+
9
+ - **`harness-device stop | start | restart`, graceful, on macOS and Linux.** Stop holds the heal job, closes public URLs, waits for every agent session to finish its turn (`--timeout`, default 120 s; `--now` skips), ends sessions with `/exit` and registered processes with Ctrl-C, closes the browser over CDP so its tabs come back, then stops the services. It stays stopped, also across reboots and logins (`launchctl disable` / `systemctl --user disable`), until `start`. `restart` is a stop followed by a start; every session resumes its pinned conversation, and the device starts again even if stopping fails.
10
+ - **`device_restart` MCP tool:** a session can ask for a graceful restart (you approve it; it runs detached and resumes the session afterwards). `stop`/`start` stay at the machine: they are denied to sessions.
11
+ - `status` shows when the device was stopped on purpose; the heal job leaves a stopped device alone.
12
+
3
13
  ## 0.1.4
4
14
 
5
15
  - **Upgrades without downtime:** `harness-device upgrade [--check] [--to x.y.z]` and an `upgrade` MCP tool (approved in the session). The new version installs next to the running copy, is verified, swapped in, and applied gracefully: only changed services restart, tmux and its sessions never do. A failure rolls back to the previous copy. Automatic every `AUTO_UPGRADE_HOURS` (6) within `AUTO_UPGRADE` (`minor` by default; `patch`, `all`, `off`); deferred while the device is busy; never for source-folder installs.
package/README.md CHANGED
@@ -125,6 +125,20 @@ harness-device doctor # "Dokploy API accepts the key"
125
125
 
126
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
127
 
128
+ ### Stop, start, restart
129
+
130
+ Run these on the machine (a terminal or SSH), not from a session: stopping ends every session.
131
+
132
+ ```bash
133
+ harness-device stop # graceful: waits for agent turns to finish (up to --timeout 120 s), ends
134
+ # sessions with /exit and processes with Ctrl-C, saves the browser's tabs;
135
+ # stays stopped, also after a reboot or login, until start
136
+ harness-device start # everything comes back; each session resumes its pinned conversation
137
+ harness-device restart # graceful stop, then start
138
+ ```
139
+
140
+ `--now` ends sessions without waiting for their turn. A session can ask for a restart with the `device_restart` tool (you approve it); it ends with the others and resumes its conversation about a minute later. `harness-device restart <service>` still restarts one service.
141
+
128
142
  ### Updating
129
143
 
130
144
  **Automatic, no downtime.** Every `AUTO_UPGRADE_HOURS` (default 6) the heal job checks npm. A newer version within `AUTO_UPGRADE` (`patch`, `minor` by default, `all`, or `off`) is installed next to the running copy, checked, swapped in, and applied by the new version in graceful mode:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
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/sh/bin/hd-heal CHANGED
@@ -3,6 +3,8 @@
3
3
  # macOS). Restarts dead or hung services, rebuilds tmux windows from state.
4
4
  set -uo pipefail
5
5
  . "$(dirname "$0")/hd-lib.sh"
6
+ # Stopped or mid-restart on purpose (harness-device stop|restart): leave everything alone.
7
+ if [ -e "$HD_STATE/stopped" ] || [ -e "$HD_STATE/restarting" ]; then exit 0; fi
6
8
  # HD_UNITS (runtime.env) lists the services the enabled capabilities own.
7
9
  # tmux is handled below (its session is the thing to check); heal is us.
8
10
  for u in ${HD_UNITS:-}; do
@@ -8,13 +8,14 @@ name="$1"
8
8
  f="$HD_STATE/procs/$name"
9
9
  hd_strip_anthropic
10
10
  delay=2
11
- while [ -f "$f.cmd" ]; do
11
+ while [ -f "$f.cmd" ] && [ ! -e "$HD_STATE/stopping" ]; do
12
12
  cd "$(cat "$f.dir" 2>/dev/null || echo "$HOME")" || exit 1
13
13
  started=$(date +%s)
14
14
  hd_log "proc $name: $(cat "$f.cmd")"
15
15
  bash -c "$(cat "$f.cmd")"
16
16
  code=$?
17
17
  [ -f "$f.cmd" ] || break
18
+ [ -e "$HD_STATE/stopping" ] && { hd_log "proc $name ended (device stopping)"; exit 0; }
18
19
  ran=$(( $(date +%s) - started ))
19
20
  if [ "$ran" -ge 120 ]; then delay=2; else delay=$(( delay * 2 )); [ "$delay" -gt 120 ] && delay=120; fi
20
21
  hd_log "proc $name exited with $code after ${ran}s; restarting in ${delay}s"
package/sh/bin/hd-rc-loop CHANGED
@@ -12,6 +12,8 @@ slotf="$HD_STATE/sessions/$name/$slot"
12
12
 
13
13
  delay=2; fast=0
14
14
  while true; do
15
+ # harness-device stop/restart ends sessions on purpose: don't serve again.
16
+ [ -e "$HD_STATE/stopping" ] && { hd_log "device is stopping; $name/$slot not restarted"; exit 0; }
15
17
  [ "$slot" = - ] || [ -f "$slotf" ] || { hd_log "slot $name/$slot was removed; stopping"; exit 0; }
16
18
  started=$(date +%s)
17
19
  if [ "$slot" = - ]; then
@@ -23,6 +25,7 @@ while true; do
23
25
  "$(dirname "$0")/hd-serve-${HD_PROVIDER:-claude}" "$label" "$id"
24
26
  fi
25
27
  code=$?
28
+ [ -e "$HD_STATE/stopping" ] && { hd_log "device is stopping; $name/$slot ended (code $code)"; exit 0; }
26
29
  ran=$(( $(date +%s) - started ))
27
30
  if [ "$ran" -ge 300 ]; then delay=2; fast=0; else delay=$(( delay * 2 )); fast=$(( fast + 1 )); [ "$delay" -gt 300 ] && delay=300; fi
28
31
  # Never swap the conversation automatically: a fast failure is usually a
@@ -92,6 +92,7 @@ The device guards its resources. Before heavy work (builds, test runs, container
92
92
 
93
93
  ### Upgrades
94
94
  harness-device upgrades itself from npm (AUTO_UPGRADE, default minor) without stopping sessions or unchanged services. \`upgrade\` with check=true shows what is available; a newer version applies to this session's device tools when the session next restarts.
95
+ - To upgrade the device, call \`upgrade\` (\`check: true\` first to see what's available): npm installs go to the newest version, source-folder installs apply the folder's current code; by default the device then restarts gracefully so every session loads the new tools. To restart the whole device without upgrading (when things are wedged), call \`device_restart\`. Either way, tell the user first that this session ends and resumes in about a minute. Stopping the device (\`harness-device stop\`/\`start\`) is done at the machine.
95
96
  - 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.`,
96
97
  },
97
98
 
package/src/cli.js CHANGED
@@ -12,6 +12,7 @@ import * as device from './device.js';
12
12
  import * as state from './state.js';
13
13
  import * as ngrok from './ngrok.js';
14
14
  import * as fleet from './fleet.js';
15
+ import * as lifecycle from './lifecycle.js';
15
16
  import * as resources from './resources.js';
16
17
  import * as upgrader from './upgrade.js';
17
18
  import { PKG, log, color, run, writeFile, capture } from './util.js';
@@ -47,7 +48,13 @@ ${color.bold('Device')}
47
48
  restart <service> restart one harness service (chromium, ttyd, ...)
48
49
  resources [--json] CPU, RAM and disk now, with the guard's level (ok, high, critical)
49
50
  gate [--force] [--wait 300] wait until the device can take new work (exit 3 if refused)
51
+ stop [--now] [--timeout 120] graceful shutdown: waits for agent turns to finish, ends sessions and processes
52
+ cleanly, saves the browser; stays stopped (also after reboots) until start
53
+ start start everything; every session resumes its conversation
54
+ restart [--now] [--timeout 120] graceful stop, then start (restart <service> restarts one service)
50
55
  upgrade [--check] [--to x.y.z] upgrade from npm without stopping sessions (AUTO_UPGRADE does it on its own)
56
+ upgrade --apply apply the installed code now (source-folder devices: after updating the folder)
57
+ [--restart] then restart gracefully so sessions load the new tools
51
58
  mcp run the harness-device MCP server (stdio)
52
59
 
53
60
  ${color.bold('Fleet')} (from any machine with ssh access to the devices)
@@ -58,8 +65,8 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
58
65
  Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
59
66
  `;
60
67
 
61
- const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook'];
62
- const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait'];
68
+ const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart'];
69
+ const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
63
70
 
64
71
  // Commands whose tail is someone else's command line, kept verbatim:
65
72
  // `proc add <name> <dir> <command...>` and `fleet run <device> <args...>`.
@@ -129,6 +136,7 @@ function setSecret(file, key, value) {
129
136
 
130
137
  function printStatus(s) {
131
138
  console.log(`${color.bold(s.device)} ${color.dim(`· ${s.provider} · ${s.serveMode} mode · ${s.capabilities.join(', ')}`)}`);
139
+ if (s.stopped) console.log(color.yellow(`stopped on purpose since ${s.stopped.since} (${s.stopped.why}); start it with: harness-device start`));
132
140
  if (s.resources) {
133
141
  const r = s.resources;
134
142
  const paint = r.level === 'critical' ? color.red : r.level === 'high' ? color.yellow : color.green;
@@ -197,6 +205,26 @@ export async function main(argv) {
197
205
  const ctx = loadContext(env);
198
206
  const to = f.to && String(f.to);
199
207
  if (to && !/^\d+\.\d+\.\d+$/.test(to)) throw new Error('--to takes a version such as 0.2.0');
208
+ const stamp = (m) => console.log(`[${new Date().toISOString()}] ${m}`.trimEnd());
209
+ // After an upgrade or apply: restart gracefully so sessions load the new tools (they resume their conversations).
210
+ const thenRestart = async () => {
211
+ if (!f.restart) return;
212
+ stamp('restarting the device so sessions load the new version');
213
+ await lifecycle.restartDevice(ctx, { except: f.except ? [String(f.except)] : [], log: stamp, why: 'after upgrade' });
214
+ };
215
+ if (f.apply) {
216
+ if (f.detach) {
217
+ // Run from a session's shell: don't wait for that session (its turn is still open).
218
+ const except = f.except ? String(f.except) : ownWindow();
219
+ ctx.platform.spawnDetached(ctx, 'upgrade', [path.join(ctx.paths.bin, 'harness-device'), 'upgrade', '--apply', ...(f.restart ? ['--restart'] : []), ...(except ? ['--except', except] : [])], path.join(ctx.paths.logs, 'upgrade.log'));
220
+ return console.log('applying in the background (harness-device logs upgrade)');
221
+ }
222
+ if (f.restart && process.env.TMUX_PANE && ownWindow() && !f.force) throw new Error('This shell runs inside the harness tmux session, which the restart ends (and this command with it). Add --detach to run it in the background.');
223
+ const r = upgrader.applyCurrent(ctx, { log: stamp });
224
+ stamp(`applied ${r.version} (${r.source})`);
225
+ await thenRestart();
226
+ return log.ok(`Applied ${r.version}.${f.restart ? ' Device restarted; sessions resume their conversations.' : ' Sessions get the new tools when they next restart (harness-device restart).'}`);
227
+ }
200
228
  if (f.check) {
201
229
  const c = await upgrader.check(ctx, { to });
202
230
  if (f.json) return console.log(JSON.stringify(c, null, 2));
@@ -210,10 +238,11 @@ export async function main(argv) {
210
238
  const go = f.auto ? c.autoAllowed : c.available && c.source === 'npm';
211
239
  if (!go) return console.log(`no upgrade: ${c.note || `on ${c.current}, latest ${c.latest}`}`);
212
240
  const bin = path.join(ctx.paths.bin, 'harness-device');
213
- ctx.platform.spawnDetached(ctx, 'upgrade', [bin, 'upgrade', ...(f.auto ? ['--auto'] : []), '--to', c.latest], path.join(ctx.paths.logs, 'upgrade.log'));
241
+ ctx.platform.spawnDetached(ctx, 'upgrade', [bin, 'upgrade', ...(f.auto ? ['--auto'] : []), ...(f.restart ? ['--restart'] : []), ...(f.except ? ['--except', String(f.except)] : []), '--to', c.latest], path.join(ctx.paths.logs, 'upgrade.log'));
214
242
  return console.log(`upgrading ${c.current} → ${c.latest} in the background (harness-device logs upgrade)`);
215
243
  }
216
- const r = await upgrader.upgrade(ctx, { to, auto: !!f.auto, log: (m) => console.log(`[${new Date().toISOString()}] ${m}`.trimEnd()) });
244
+ const r = await upgrader.upgrade(ctx, { to, auto: !!f.auto, log: stamp });
245
+ if (r.upgraded) await thenRestart();
217
246
  if (f.json) return console.log(JSON.stringify(r, null, 2));
218
247
  return r.upgraded ? log.ok(`Upgraded ${r.from} → ${r.to}. ${r.note}`) : console.log(`no upgrade: ${r.note || `on ${r.current}, latest ${r.latest}`}`);
219
248
  }
@@ -426,8 +455,37 @@ export async function main(argv) {
426
455
  return;
427
456
  }
428
457
 
458
+ case 'stop':
459
+ case 'start': {
460
+ const ctx = loadContext(env);
461
+ const say = (m) => console.log(color.dim(` ${m}`));
462
+ if (cmd === 'start') {
463
+ await lifecycle.startDevice(ctx, { log: say });
464
+ return log.ok('Started. harness-device status shows the sessions as they come back.');
465
+ }
466
+ if (process.env.TMUX_PANE && ownWindow() && !f.force) throw new Error('This shell runs inside the harness tmux session, which stop ends. Run it from a plain terminal or SSH shell, or add --force.');
467
+ const timeoutMs = f.timeout ? Math.max(0, Number(f.timeout)) * 1000 : 120000;
468
+ if (!Number.isFinite(timeoutMs)) throw new Error('--timeout takes seconds');
469
+ await lifecycle.stopDevice(ctx, { now: !!f.now, timeoutMs, log: say });
470
+ return log.ok('Stopped. It stays stopped, also after a reboot, until: harness-device start');
471
+ }
472
+
429
473
  case 'restart': {
430
- if (!sub) throw new Error('usage: restart <service>');
474
+ if (!sub) {
475
+ const ctx = loadContext(env);
476
+ const say = (m) => console.log(color.dim(` ${m}`));
477
+ const timeoutMs = f.timeout ? Math.max(0, Number(f.timeout)) * 1000 : 120000;
478
+ if (!Number.isFinite(timeoutMs)) throw new Error('--timeout takes seconds');
479
+ if (process.env.TMUX_PANE && ownWindow() && !f.detach && !f.force) throw new Error('This shell runs inside the harness tmux session, which a restart ends. Run it from a plain terminal, add --detach (runs in the background), or --force.');
480
+ if (f.detach) {
481
+ const bin = path.join(ctx.paths.bin, 'harness-device');
482
+ const own = ownWindow();
483
+ ctx.platform.spawnDetached(ctx, 'restart', [bin, 'restart', ...(f.now ? ['--now'] : []), '--timeout', String(timeoutMs / 1000), ...(own ? ['--except', own] : []), '--force'], path.join(ctx.paths.logs, 'restart.log'));
484
+ return console.log('restarting in the background (harness-device logs restart); sessions resume their conversations');
485
+ }
486
+ await lifecycle.restartDevice(ctx, { now: !!f.now, timeoutMs, except: f.except ? [String(f.except)] : [], log: say });
487
+ return log.ok('Restarted. Sessions are resuming their conversations (harness-device status).');
488
+ }
431
489
  const ctx = loadContext(env);
432
490
  const tmux = device.isTmux(sub);
433
491
  if (tmux && process.env.TMUX_PANE && !f.force) throw new Error('This shell runs inside the harness tmux session: restarting tmux would end it, and every Remote Control session. Run it from a plain SSH shell, or add --force.');
package/src/device.js CHANGED
@@ -8,6 +8,7 @@ import { capture, ok, httpJson, which } from './util.js';
8
8
  import { listSessions, listProcs, recentEvents } from './state.js';
9
9
  import { loadConfig, saveConfig, mergePorts } from './config.js';
10
10
  import * as ngrok from './ngrok.js';
11
+ import { isStopped } from './lifecycle.js';
11
12
  import * as resources from './resources.js';
12
13
 
13
14
  const short = (u) => u.replace(/^harness-/, '');
@@ -48,6 +49,7 @@ export async function status(ctx) {
48
49
  provider: ctx.cfg.PROVIDER,
49
50
  capabilities: ctx.caps.map((c) => c.id),
50
51
  serveMode: ctx.cfg.SERVE_MODE,
52
+ stopped: isStopped(ctx),
51
53
  sessions: listSessions(ctx),
52
54
  procs: listProcs(ctx),
53
55
  events: recentEvents(ctx, 10),
@@ -62,7 +64,7 @@ export async function status(ctx) {
62
64
  export function logs(ctx, target, lines = 100) {
63
65
  const n = Math.max(1, Math.min(2000, Number(lines) || 100));
64
66
  const proj = ctx.projects.find((p) => p.name === target);
65
- if (proj || target === 'tests' || target === 'upgrade' || /^(rc|proc)-[A-Za-z0-9_-]+$/.test(target)) {
67
+ if (proj || ['tests', 'upgrade', 'restart'].includes(target) || /^(rc|proc)-[A-Za-z0-9_-]+$/.test(target)) {
66
68
  const file = path.join(ctx.paths.logs, proj ? `rc-${proj.name}.log` : `${target}.log`);
67
69
  return fs.existsSync(file) ? capture('tail', ['-n', String(n), file]) : `(no log yet: ${file})`;
68
70
  }
@@ -0,0 +1,139 @@
1
+ // Graceful stop, start and restart of the whole device, on both platforms.
2
+ //
3
+ // Stop: hold the heal job (it would restart what we stop), close public URLs,
4
+ // wait for every agent session to finish its turn, end sessions and processes
5
+ // the way a user would (/exit, Ctrl-C), close the browser over CDP so its tabs
6
+ // are saved, then stop the services. `stop` keeps the device stopped (also
7
+ // across reboots) until `start`; `restart` starts it again right away, and
8
+ // every session resumes its pinned conversation.
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { capture, ok, httpJson } from './util.js';
13
+ import { listSessions, listProcs, event } from './state.js';
14
+
15
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
16
+ const flag = (ctx, name) => path.join(ctx.paths.state, name);
17
+ const tmux = (ctx, args) => ok('tmux', args, { env: ctx.env });
18
+ const target = (ctx, win) => `=${ctx.cfg.SESSION}:${win}`;
19
+ /** Claude Code shows this while a turn is running. */
20
+ const BUSY = /esc to interrupt/i;
21
+
22
+ function setFlag(ctx, name, why) {
23
+ fs.mkdirSync(ctx.paths.state, { recursive: true });
24
+ fs.writeFileSync(flag(ctx, name), `${new Date().toISOString()} ${why}\n`);
25
+ }
26
+ const clearFlag = (ctx, name) => fs.rmSync(flag(ctx, name), { force: true });
27
+
28
+ /** { since, why } when the device was stopped on purpose, else null. */
29
+ export function isStopped(ctx) {
30
+ const f = flag(ctx, 'stopped');
31
+ if (!fs.existsSync(f)) return null;
32
+ const [since, ...why] = fs.readFileSync(f, 'utf8').trim().split(' ');
33
+ return { since, why: why.join(' ') };
34
+ }
35
+
36
+ /** A session is busy while its transcript changed in the last `quietMs` or its pane shows a running turn. */
37
+ export function sessionBusy(ctx, s, { quietMs = 10000, now = Date.now() } = {}) {
38
+ if (!s.running) return false;
39
+ if (s.transcript && fs.existsSync(s.transcript) && now - fs.statSync(s.transcript).mtimeMs < quietMs) return true;
40
+ const pane = capture('tmux', ['capture-pane', '-p', '-t', target(ctx, s.window)], { env: ctx.env });
41
+ return BUSY.test(pane || '');
42
+ }
43
+
44
+ /** Wait until no session is busy, or the timeout. Returns the windows still busy. */
45
+ async function waitIdle(ctx, { timeoutMs, log, except = [] }) {
46
+ const end = Date.now() + timeoutMs;
47
+ let busy = [];
48
+ for (;;) {
49
+ busy = listSessions(ctx).filter((s) => !except.includes(s.window) && sessionBusy(ctx, s));
50
+ if (!busy.length || Date.now() >= end) return busy.map((s) => s.window);
51
+ log(`waiting for ${busy.map((s) => s.window).join(', ')} to finish (${Math.ceil((end - Date.now()) / 1000)}s left)`);
52
+ await sleep(Math.min(5000, Math.max(250, end - Date.now())));
53
+ }
54
+ }
55
+
56
+ const windowAlive = (ctx, win) => (capture('tmux', ['list-windows', '-t', `=${ctx.cfg.SESSION}`, '-F', '#{window_name}'], { env: ctx.env }) || '').split('\n').includes(win);
57
+
58
+ /** Send keys, wait for the window to close, escalate to Ctrl-C, then kill it. */
59
+ async function endWindow(ctx, win, first, { waitMs }) {
60
+ if (!windowAlive(ctx, win)) return 'gone';
61
+ for (const keys of first) tmux(ctx, ['send-keys', '-t', target(ctx, win), ...keys]);
62
+ for (const [keys, ms] of [[null, waitMs], [['C-c'], 3000], [['C-c'], 3000]]) {
63
+ if (keys) tmux(ctx, ['send-keys', '-t', target(ctx, win), ...keys]);
64
+ for (const end = Date.now() + ms; Date.now() < end; await sleep(250)) if (!windowAlive(ctx, win)) return 'exited';
65
+ }
66
+ tmux(ctx, ['kill-window', '-t', target(ctx, win)]);
67
+ return 'killed';
68
+ }
69
+
70
+ /** Ask Chromium to close itself, so it saves its session (tabs come back). */
71
+ async function closeBrowser(ctx) {
72
+ if (!ctx.caps.some((c) => c.id === 'browser')) return 'off';
73
+ const v = await httpJson(`http://127.0.0.1:${ctx.cfg.CDP_PORT}/json/version`, 2000);
74
+ if (!v || !v.webSocketDebuggerUrl || typeof WebSocket === 'undefined') return 'not running';
75
+ return new Promise((resolve) => {
76
+ const ws = new WebSocket(v.webSocketDebuggerUrl);
77
+ const done = (r) => { clearTimeout(t); try { ws.close(); } catch {} resolve(r); };
78
+ const t = setTimeout(() => done('timeout'), 5000);
79
+ ws.onopen = () => ws.send(JSON.stringify({ id: 1, method: 'Browser.close' }));
80
+ ws.onmessage = () => done('closed');
81
+ ws.onclose = () => done('closed');
82
+ ws.onerror = () => done('error');
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Stop the device gracefully.
88
+ * persist: stay stopped (also after a reboot) until start. restart uses false.
89
+ * now: don't wait for sessions to finish their turn.
90
+ * except: windows not to wait for (the session that asked for a restart).
91
+ */
92
+ export async function stopDevice(ctx, { persist = true, now = false, timeoutMs = 120000, except = [], log = () => {}, why = 'stop' } = {}) {
93
+ setFlag(ctx, persist ? 'stopped' : 'restarting', why);
94
+ log(persist ? 'stopping the device (it stays stopped until: harness-device start)' : 'restarting the device');
95
+ if (ctx.caps.some((c) => c.id === 'ngrok')) { ctx.platform.ngrokDown(ctx); log('public URLs closed'); }
96
+
97
+ if (!now) {
98
+ const busy = await waitIdle(ctx, { timeoutMs, log, except });
99
+ if (busy.length) log(`still busy after ${Math.round(timeoutMs / 1000)}s, ending anyway: ${busy.join(', ')}`);
100
+ }
101
+ setFlag(ctx, 'stopping', why);
102
+ const sessions = listSessions(ctx).filter((s) => s.running);
103
+ const procs = listProcs(ctx).filter((p) => p.running);
104
+ const ended = await Promise.all([
105
+ ...sessions.map(async (s) => `${s.window} ${await endWindow(ctx, s.window, [['Escape'], ['C-u'], ['/exit', 'Enter']], { waitMs: 15000 })}`),
106
+ ...procs.map(async (p) => `proc-${p.name} ${await endWindow(ctx, `proc-${p.name}`, [['C-c']], { waitMs: 10000 })}`),
107
+ ]);
108
+ if (ended.length) log(`ended: ${ended.join(', ')}`);
109
+ const b = await closeBrowser(ctx);
110
+ if (b !== 'off') log(`browser: ${b}`);
111
+ ctx.platform.stopServices(ctx, { persist });
112
+ clearFlag(ctx, 'stopping');
113
+ event(ctx, persist ? `device stopped (${why})` : `device stopping for a restart (${why})`);
114
+ log('services stopped');
115
+ return { stopped: true, persist, ended, browser: b };
116
+ }
117
+
118
+ /** Start everything again; every session resumes its pinned conversation. */
119
+ export async function startDevice(ctx, { log = () => {}, why = 'start' } = {}) {
120
+ clearFlag(ctx, 'stopping');
121
+ clearFlag(ctx, 'stopped');
122
+ ctx.platform.startServices(ctx);
123
+ clearFlag(ctx, 'restarting');
124
+ event(ctx, `device started (${why})`);
125
+ log('services started; sessions resume their conversations');
126
+ return { started: true };
127
+ }
128
+
129
+ /** Graceful stop (not persisted), then start. */
130
+ export async function restartDevice(ctx, opts = {}) {
131
+ const why = opts.why || 'restart';
132
+ try {
133
+ await stopDevice(ctx, { ...opts, persist: false, why });
134
+ } finally {
135
+ // Whatever happened while stopping, never leave the device down after a restart.
136
+ await startDevice(ctx, { log: opts.log, why });
137
+ }
138
+ return { restarted: true };
139
+ }
package/src/mcp/server.js CHANGED
@@ -10,7 +10,7 @@ import { loadContext } from '../context.js';
10
10
  import * as device from '../device.js';
11
11
  import * as state from '../state.js';
12
12
  import * as ngrok from '../ngrok.js';
13
- import { PKG, sendChildOutputToStderr } from '../util.js';
13
+ import { PKG, sendChildOutputToStderr, capture } from '../util.js';
14
14
  import { SETTABLE_KEYS, setConfigValue } from '../config.js';
15
15
  import * as resources from '../resources.js';
16
16
  import * as upgrader from '../upgrade.js';
@@ -183,14 +183,32 @@ export function buildServer(env = process.env) {
183
183
  tool('resources', 'CPU, RAM and disk (persistent storage) on this device now, with the resource guard\'s level: ok, high or critical. Check it before heavy work (builds, test runs, containers, big installs).', {},
184
184
  async (c) => text(await resources.sample(c)));
185
185
 
186
- tool('upgrade', 'Check for a newer harness-device on npm, or upgrade to it (the user approves this call). Upgrades run in the background without stopping sessions or unchanged services; the device also does this on its own per AUTO_UPGRADE. check=true only reports.',
187
- { check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional() },
186
+ tool('upgrade', 'Upgrade harness-device on this device (the user approves this call); check=true only reports. npm installs go to the newest version (or `version`); source-folder installs apply the folder\'s current code. Runs in the background without stopping sessions or unchanged services. restart (default true) then restarts the device gracefully so every session, this one included, loads the new tools and resumes its conversation about a minute later: tell the user before calling.',
187
+ { check: z.boolean().optional(), version: z.string().regex(/^\d+\.\d+\.\d+$/).optional(), restart: z.boolean().optional() },
188
188
  async (c, a) => {
189
189
  const chk = await upgrader.check(c, { to: a.version });
190
- if (a.check || !chk.available || chk.source !== 'npm') return text(chk);
191
- if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `Upgrade harness-device ${chk.current} → ${chk.latest} now? Sessions keep running; only services whose definitions changed restart.`);
192
- c.platform.spawnDetached(c, 'upgrade', [path.join(c.paths.bin, 'harness-device'), 'upgrade', '--to', chk.latest], path.join(c.paths.logs, 'upgrade.log'));
193
- return text(`Upgrading ${chk.current} → ${chk.latest} in the background. Follow it with the logs tool, target "upgrade"; this session gets the new tools when it next restarts.`);
190
+ if (a.check) return text(chk);
191
+ const restart = a.restart !== false;
192
+ const folder = chk.source === 'folder';
193
+ if (!folder && !chk.available) return text({ ...chk, note: chk.note || `already on ${chk.current}` });
194
+ if (chk.source === 'none') return text({ ...chk, note: 'not installed on this device yet' });
195
+ const what = folder ? `Apply the harness-device code in its source folder (${chk.current}) now?` : `Upgrade harness-device ${chk.current} → ${chk.latest} now?`;
196
+ if (server.server.getClientCapabilities()?.elicitation) await confirm(server, `${what} Sessions keep running while it installs${restart ? '; then the device restarts gracefully and every session (this one too) resumes its conversation in about a minute' : ''}.`);
197
+ const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
198
+ const args = [path.join(c.paths.bin, 'harness-device'), 'upgrade', ...(folder ? ['--apply'] : ['--to', chk.latest]), ...(restart ? ['--restart'] : []), ...(own ? ['--except', own] : [])];
199
+ c.platform.spawnDetached(c, 'upgrade', args, path.join(c.paths.logs, 'upgrade.log'));
200
+ return text(`${folder ? `Applying ${chk.current} from the source folder` : `Upgrading ${chk.current} → ${chk.latest}`} in the background (logs tool, target "upgrade").${restart ? ' The device then restarts gracefully; this session ends and resumes the same conversation about a minute later.' : ' Sessions get the new tools at their next restart (device_restart).'}`);
201
+ });
202
+
203
+ tool('device_restart', 'Gracefully restart the whole device (the user approves this call): waits for other sessions to finish their turn, ends sessions and processes cleanly, saves the browser, restarts every service. This session ends too and resumes the same conversation about a minute later; tell the user before calling. Stopping the device is done at the machine (harness-device stop), not from a session.',
204
+ { now: z.boolean().optional().describe("don't wait for other sessions to finish their turn") },
205
+ async (c, a) => {
206
+ if (server.server.getClientCapabilities()?.elicitation) await confirm(server, 'Restart the whole device now? Every session (this one too) ends and resumes its conversation in about a minute; public URLs close.');
207
+ // The calling session's own turn is still open: don't wait for it.
208
+ const own = c.env.TMUX_PANE ? capture('tmux', ['display-message', '-p', '-t', c.env.TMUX_PANE, '#{window_name}'], { env: c.env }) : '';
209
+ const bin = path.join(c.paths.bin, 'harness-device');
210
+ c.platform.spawnDetached(c, 'restart', [bin, 'restart', '--force', ...(a.now ? ['--now'] : []), ...(own ? ['--except', own] : [])], path.join(c.paths.logs, 'restart.log'));
211
+ return text('Restarting in the background (log: logs tool, target "restart"). This session ends shortly and resumes the same conversation; public URLs stay closed until reopened.');
194
212
  });
195
213
 
196
214
  tool('config_get', `Current device settings that can be changed with config_set: ${Object.keys(SETTABLE_KEYS).join(', ')}.`, {},
@@ -246,3 +246,35 @@ export function spawnDetached(ctx, name, args, logFile) {
246
246
  fs.closeSync(fd);
247
247
  return child.pid;
248
248
  }
249
+
250
+ /** Stop order: heal first (it would restart the rest), tmux last. */
251
+ const STOP_ORDER = (units) => ['harness-heal', ...units.filter((u) => !['harness-heal', 'harness-tmux'].includes(u)), 'harness-tmux'].filter((u) => units.includes(u));
252
+
253
+ /**
254
+ * Unload every harness job. persist: also `launchctl disable`, so they don't
255
+ * load at the next login until startServices. The plists stay in place.
256
+ */
257
+ export function stopServices(ctx, { persist = false, dryRun = false } = {}) {
258
+ const list = [...STOP_ORDER(ctx.units), 'harness-ngrok'];
259
+ for (const u of list) {
260
+ const l = labelOf(u);
261
+ if (persist) lc(['disable', `${domain()}/${l}`], { dryRun });
262
+ if (!dryRun && !loaded(l)) continue;
263
+ lc(['bootout', `${domain()}/${l}`], { dryRun });
264
+ for (let i = 0; !dryRun && i < 20 && loaded(l); i++) sleepMs(250);
265
+ }
266
+ // The tmux server outlives its supervisor job by design; end it explicitly.
267
+ run('tmux', ['kill-session', '-t', `=${ctx.cfg.SESSION}`], { dryRun, allowFail: true, env: ctx.env });
268
+ }
269
+
270
+ /** Enable and load every harness job again (tmux first, heal last). */
271
+ export function startServices(ctx, { dryRun = false } = {}) {
272
+ const dir = serviceDir(ctx.env);
273
+ for (const u of [...STOP_ORDER(ctx.units)].reverse()) {
274
+ const l = labelOf(u);
275
+ lc(['enable', `${domain()}/${l}`], { dryRun });
276
+ const file = path.join(dir, plistName(u));
277
+ if (!dryRun && !fs.existsSync(file)) { console.log(color.yellow(` ! ${file} is missing: run harness-device install`)); continue; }
278
+ if (dryRun || !loaded(l)) bootstrap(file, l, { dryRun });
279
+ }
280
+ }
@@ -157,3 +157,24 @@ export function spawnDetached(ctx, name, args, logFile) {
157
157
  return run('systemd-run', ['--user', '--quiet', '--collect', `--unit=harness-${name}-${Date.now()}`, ...setenv,
158
158
  '/bin/sh', '-c', 'exec "$0" "$@" >> "' + logFile.replace(/"/g, '') + '" 2>&1', ...args], { env, allowFail: true });
159
159
  }
160
+
161
+ /**
162
+ * Stop every harness service (heal timer first, tmux last). persist: also
163
+ * disable them, so they stay stopped after a reboot until startServices.
164
+ */
165
+ export function stopServices(ctx, { persist = false, dryRun = false } = {}) {
166
+ const env = userEnv(ctx.env);
167
+ const units = ctx.units.filter((u) => u !== 'harness-heal' && u !== 'harness-tmux');
168
+ sysd(['stop', 'harness-heal.timer', 'harness-heal.service'], env, { dryRun, allowFail: true });
169
+ sysd(['stop', 'harness-ngrok.service'], env, { dryRun, allowFail: true });
170
+ if (units.length) sysd(['stop', ...units.map(unitName)], env, { dryRun, allowFail: true });
171
+ sysd(['stop', 'harness-tmux.service', 'harness.target'], env, { dryRun, allowFail: true });
172
+ if (persist) sysd(['disable', 'harness.target', 'harness-heal.timer'], env, { dryRun, allowFail: true });
173
+ }
174
+
175
+ /** Enable and start everything again. */
176
+ export function startServices(ctx, { dryRun = false } = {}) {
177
+ const env = userEnv(ctx.env);
178
+ sysd(['enable', 'harness.target', 'harness-heal.timer'], env, { dryRun });
179
+ sysd(['start', 'harness.target', 'harness-heal.timer'], env, { dryRun });
180
+ }
@@ -188,7 +188,9 @@ export function pathRule(tool, abs, home) {
188
188
  * ngrok_up, proc_add, ...), never by hand.
189
189
  */
190
190
  export const DEVICE_ADMIN_DENY = ['Bash(harness-device init:*)', 'Bash(harness-device install:*)',
191
- 'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)'];
191
+ 'Bash(harness-device uninstall:*)', 'Bash(harness-device secrets:*)',
192
+ // Stopping ends every session and none could start the device again; restart goes through device_restart.
193
+ 'Bash(harness-device stop:*)', 'Bash(harness-device start:*)', 'Bash(harness-device restart)', 'Bash(harness-device restart --:*)'];
192
194
 
193
195
  /**
194
196
  * Wire everything into Claude Code. ctx: { cfg, caps, projects, paths, env, dryRun, mcpServers }
package/src/upgrade.js CHANGED
@@ -149,3 +149,18 @@ export async function upgrade(ctx, { to, auto = false, log = () => {} } = {}) {
149
149
  unlock();
150
150
  }
151
151
  }
152
+
153
+ /**
154
+ * Apply the code that is installed now (npm copy or source folder) to the
155
+ * running device, gracefully: scripts, service files, MCP/skill/permissions.
156
+ * Sessions and unchanged services keep running. For a source-folder device
157
+ * this is how an updated folder (git pull, local edits) goes live.
158
+ */
159
+ export function applyCurrent(ctx, { log = () => {} } = {}) {
160
+ const inst = installed(ctx);
161
+ if (inst.source === 'none') throw new Error('harness-device is not installed on this device yet (run harness-device install on the machine).');
162
+ const ok = applyInstalled(ctx, log);
163
+ event(ctx, ok ? `applied harness-device ${inst.version} (${inst.source})` : `applying harness-device ${inst.version} failed; see harness-device logs upgrade`);
164
+ if (!ok) throw new Error('applying failed; see harness-device logs upgrade');
165
+ return { applied: true, version: inst.version, source: inst.source };
166
+ }