@dreamtree-org/harness-device 0.1.5 → 0.1.7

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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.7
4
+
5
+ - **Linux: upgrades and uninstall no longer fail on systemd's `harness.target.wants/` folder.** The installer took the folder for an old unit file and tried to delete it (EISDIR), so from 0.1.4 to 0.1.6 every upgrade after the first install was rolled back. An upgrade runs the new version's installer, so upgrading to 0.1.7 fixes an affected device with no manual steps.
6
+
7
+ ## 0.1.6
8
+
9
+ - **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.
10
+
3
11
  ## 0.1.5
4
12
 
5
13
  - **`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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dreamtree-org/harness-device",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
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",
@@ -92,7 +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 restart the whole device (after an upgrade, or when things are wedged), call \`device_restart\`; 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
+ - 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.
96
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.`,
97
97
  },
98
98
 
package/src/cli.js CHANGED
@@ -53,6 +53,8 @@ ${color.bold('Device')}
53
53
  start start everything; every session resumes its conversation
54
54
  restart [--now] [--timeout 120] graceful stop, then start (restart <service> restarts one service)
55
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
56
58
  mcp run the harness-device MCP server (stdio)
57
59
 
58
60
  ${color.bold('Fleet')} (from any machine with ssh access to the devices)
@@ -63,7 +65,7 @@ ${color.bold('Fleet')} (from any machine with ssh access to the devices)
63
65
  Capabilities: ${ORDER.map((id) => (CAPABILITIES[id].required ? `${id}*` : id)).join(', ')} (* always on)
64
66
  `;
65
67
 
66
- const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now'];
68
+ const BOOL_FLAGS = ['dryRun', 'skipSystem', 'skipPkg', 'graceful', 'json', 'purge', 'force', 'follow', 'help', 'version', 'check', 'auto', 'detach', 'hook', 'now', 'apply', 'restart'];
67
69
  const VALUE_FLAGS = ['device', 'project', 'with', 'without', 'capabilities', 'serveMode', 'provider', 'dokployUrl', 'port', 'to', 'wait', 'timeout', 'except'];
68
70
 
69
71
  // Commands whose tail is someone else's command line, kept verbatim:
@@ -203,6 +205,26 @@ export async function main(argv) {
203
205
  const ctx = loadContext(env);
204
206
  const to = f.to && String(f.to);
205
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
+ }
206
228
  if (f.check) {
207
229
  const c = await upgrader.check(ctx, { to });
208
230
  if (f.json) return console.log(JSON.stringify(c, null, 2));
@@ -216,10 +238,11 @@ export async function main(argv) {
216
238
  const go = f.auto ? c.autoAllowed : c.available && c.source === 'npm';
217
239
  if (!go) return console.log(`no upgrade: ${c.note || `on ${c.current}, latest ${c.latest}`}`);
218
240
  const bin = path.join(ctx.paths.bin, 'harness-device');
219
- 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'));
220
242
  return console.log(`upgrading ${c.current} → ${c.latest} in the background (harness-device logs upgrade)`);
221
243
  }
222
- 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();
223
246
  if (f.json) return console.log(JSON.stringify(r, null, 2));
224
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}`}`);
225
248
  }
package/src/mcp/server.js CHANGED
@@ -183,14 +183,21 @@ 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).'}`);
194
201
  });
195
202
 
196
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.',
@@ -49,13 +49,24 @@ export function renderServices(ctx, detect = true) {
49
49
  const sysd = (args, env, opts = {}) => run('systemctl', ['--user', ...args], { env, ...opts });
50
50
 
51
51
  /** Write units, drop stale ones, enable at boot, start; never restart tmux (live sessions). */
52
+ /**
53
+ * Our unit files in the user unit dir: plain files named harness[.-]…, never
54
+ * the harness.target.wants/ (or .requires/) folders systemd itself creates.
55
+ */
56
+ export function ownUnitFiles(dir) {
57
+ if (!fs.existsSync(dir)) return [];
58
+ return fs.readdirSync(dir, { withFileTypes: true })
59
+ .filter((e) => /^harness[.-]/.test(e.name) && !e.isDirectory() && !/\.(wants|requires)$/.test(e.name))
60
+ .map((e) => e.name);
61
+ }
62
+
52
63
  export function activate(ctx, files, { dryRun, graceful = false }) {
53
64
  const env = userEnv(ctx.env);
54
65
  const dir = serviceDir(env);
55
66
  // Graceful (upgrades): restart only services whose unit file changed; the rest
56
67
  // pick up new scripts at their next restart.
57
68
  const changed = new Set(Object.keys(files).filter((n) => !fs.existsSync(path.join(dir, n)) || fs.readFileSync(path.join(dir, n), 'utf8') !== files[n]));
58
- const stale = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^harness[.-]/.test(f) && !(f in files)) : [];
69
+ const stale = ownUnitFiles(dir).filter((f) => !(f in files));
59
70
  for (const f of stale) {
60
71
  sysd(['disable', '--now', f], env, { dryRun, allowFail: true });
61
72
  if (!dryRun) fs.rmSync(path.join(dir, f), { force: true });
@@ -78,7 +89,7 @@ export function deactivate(ctx, { dryRun }) {
78
89
  const env = userEnv(ctx.env);
79
90
  const dir = serviceDir(env);
80
91
  sysd(['disable', '--now', 'harness.target', 'harness-ngrok.service', ...ctx.units.map(unitName)], env, { dryRun, allowFail: true });
81
- if (fs.existsSync(dir)) for (const f of fs.readdirSync(dir).filter((f) => /^harness[.-]/.test(f))) {
92
+ for (const f of ownUnitFiles(dir)) {
82
93
  dryRun ? console.log(color.dim(` rm ${f}`)) : fs.rmSync(path.join(dir, f), { force: true });
83
94
  }
84
95
  sysd(['daemon-reload'], env, { dryRun, allowFail: true });
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
+ }